Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics with upper bound

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 to java.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.

like image 653
nilan59 Avatar asked Feb 15 '26 23:02

nilan59


2 Answers

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.

like image 185
Kayaman Avatar answered Feb 17 '26 13:02

Kayaman


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: enter image description here

like image 22
Chriss Avatar answered Feb 17 '26 15:02

Chriss



Donate For Us

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