Say I have following sample application, I'm using java 8.
I have following class that has a child class:
public class GrantedAuthority { }
public class GrantedAuthoritySubClass extends GrantedAuthority { }
Following class is where the tricky part happens:
public class UserDetails {
Collection<? extends GrantedAuthority> authorities;
public Collection<? extends GrantedAuthority> getAuthorities(){
return authorities;
}
}
My main method:
public class Main {
public static void main(String[] args) {
UserDetails u = new UserDetails();
List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
list.add(new GrantedAuthoritySubClass());
u.getAuthorities().addAll(list);
}
}
When I run this I get the following error:
Error:(12, 35) java: incompatible types:
java.util.List<GrantedAuthority>cannot be converted tojava.util.Collection<? extends capture#1 of ? extends GrantedAuthority>
My problem is, how I can pass a collection of GrantedAuthoritySubClass Objects to the collection returned by u.getAuthorities(). I can't figure it out and there are so many compilation errors attached to various ways I've tried.
According to the PECS rule, your authorities collection is a producer of elements (since it uses extends). This means that the collection can only "produce" or "output" GrantedAuthority objects or its subclasses. It also means you can't put anything into the collection since you don't know the collection's actual type.
If you used super you could put your objects there (but you couldn't get them out), but I suspect that the wildcard is completely unnecessary.
You can't compile cause you don't know what kind of Collection you get.
You need to change the signature to
Collection<? super GrantedAuthority> getAuthorities()
This illustrates the problem (c) Andrey Tyukin:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With