0

My question is an extension of this post.

If I have a method like this:

public static <E extends CharSequence, T extends E> List<T> doIt(List<E> nums) {
return null;
}

Why this code compiles ? Why super String is compatible with T extends CharSequence

public static void main(String[] args) {

    List<CharSequence> in = new ArrayList<>();

    List<? super String> result = new ArrayList<>();

    result = doIt(in);        
}
michael laudrup
  • 27
  • 3
  • 10
  • 1
    Did you see https://stackoverflow.com/questions/19795709/understanding-upper-and-lower-bounds-on-in-java-generics?rq=1? –  Jul 01 '17 at 09:07
  • I would simply the code removing the initialization of ```result```, is not adding anything to the problem and that value is overwritten immediately. – Valentin Ruano Jul 01 '17 at 23:12

1 Answers1

0

The code works because <? super String> and <? extends CharSequence> are not mutually exclusive bounds; String and CharSequence comply with both.

Notice that it works even if there is some classes that comply with one constraint but not with the other (for example Object of String but it does not extends CharSequence), so long as the intersection of both constraints is not empty.

In contrast this wouldn't work:

import java.util.*;
class Test {

   public static <E extends CharSequence, T extends E> doIt(List<E> in) {
     return null;
   }

   public static void main(String[] args) {
      final List<CharSequence> in = new ArrayList<>();
      final List<? super Integer> out = doIt(in);
   }
} 

Because there is no class that would comply with both bounds as CharSequence is not super of Integer.

Valentin Ruano
  • 2,726
  • 19
  • 29
  • Thank you for your answer. but could be that super String> and extends CharSequence> are not mutually exclusive bounds ? Can you provide an example for your second paragraph ? It's not clear – michael laudrup Jul 14 '17 at 21:30
  • @michael laudrup. What I mean with not mutually exclusive is that there are at least one class that complies with both constraints. In this case they are ```String``` and ```CharSequence``` themselves. In contrast, if you had ``` super Integer>``` rather than ``` super String>``` then there is no class that would meet both constraints... the compiler knows this because ```CharSequence``` is no super-class/interface of ```Integer```. – Valentin Ruano Jul 14 '17 at 22:26