0

If I do add in the following code, I get a compile error. In the case of extends, it is an Upper Bounded Wildcard (? extends interface or class as a). If it is a class that inherits a, I think my code should succeed. But it failed and I don't know why.

Help

this is Error Message

'add(capture<? extends org.springframework.security.core.GrantedAuthority>)' in 'java.util.Set' cannot be applied to '(org.springframework.security.core.authority.SimpleGrantedAuthority)'

this is Error Code

Set<? extends GrantedAuthority> modifiedSet = new HashSet<>();
                
SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(p.getValueAsString());

modifiedSet.add(simpleGrantedAuthority);

But again, inserting in a stream format like the one below is confusing because it works normally.

Set<? extends GrantedAuthority> authSet =
         member.getAuthorities()
            .stream()
            .map(authority -> new 
                SimpleGrantedAuthority(authority.getAuthority()))
                .collect(Collectors.toSet());
JOJU
  • 31
  • 6
  • You cannot add to a set with Set extends T> because it could be any Set where A extends T. – matt Dec 17 '21 at 12:59
  • 2
    Eg. `List extends Number> numbers = new ArrayList();` then `numbers.add( new Double(1.0);` because Double extends Number. It's not possible. – matt Dec 17 '21 at 13:00
  • Is it official in Java? I added the content, can you take a look? source code at the bottom – JOJU Dec 17 '21 at 13:01
  • 1
    Yes official. I am looking for the duplicate now. – matt Dec 17 '21 at 13:01
  • Wow, why doesn't the integer type go add it? – JOJU Dec 17 '21 at 13:03
  • 1
    You can say `List ints = Arrays.listOf( 1, 2,4);` then `List extends Number> numbers = ints;` – matt Dec 17 '21 at 13:03
  • But if you use super in your code, why does the integer add operation succeed?? super is a Lower Bounded Wildcard. – JOJU Dec 17 '21 at 13:04
  • 2
    The ? extends T means. This is a Generic of *something* that extends T. We don't know what the ? so you cannot add to the collection. You can remove ? from the collection and use the as T's. – matt Dec 17 '21 at 13:04
  • ``` List super Number> numList = new ArrayList<>(); Integer a = 10; numList.add(a);``` . this success code... – JOJU Dec 17 '21 at 13:05
  • 1
    Because all Numbers are also instances of "?" If you have a List you can add Integer, Double, Float, etc. So if you have List super Number> then you know you can add any Number class. The thing you cannot do, is get a Number out of that list. – matt Dec 17 '21 at 13:07
  • ``` a = numList.get(0); ``` error wow your very good! – JOJU Dec 17 '21 at 13:09

0 Answers0