0
   List<? super Number> myNumsContra = new ArrayList<Number>();
    myNumsContra.add(2.0F);
    myNumsContra.add(2);
    myNumsContra.add(2L);

    System.out.println(myNumsContra.get(0)); //should throw error

According to the contravariance rule for generics the get(0) call above should throw a compile error. But I don't see this happening. Is there something I missed ? I am using Java-8

jtkSource
  • 675
  • 9
  • 21
  • 1
    see the javadocs for the method you are using https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#get(int) – Scary Wombat Oct 05 '17 at 07:36
  • 2
    Why should `get(0)` exactly throw an error? – M. le Rutte Oct 05 '17 at 07:37
  • Was reading this article (https://dzone.com/articles/covariance-and-contravariance) that says if the List class had put a bound such as, ? super T, then I wouldn't be able to call get(0) as the compiler would throw an error. – jtkSource Oct 05 '17 at 07:43
  • I dont see why this needs to be down voted - I asked a valid doubt. isn't that what stack overflow is for ? – jtkSource Oct 05 '17 at 07:45
  • The downvoters thought that you are asking why you don't get an error on calling `get` itself (presumably because of the index parameter type), rather than about what you do with the result. Your question is phrased a bit misleading. – Thilo Oct 05 '17 at 07:47
  • My understanding is wrong the question is as you said – jtkSource Oct 05 '17 at 07:48

1 Answers1

4

There is no compile-time error, because println can take any Object (which is what even a ? is guaranteed to be compatible with).

The error you are looking for is

Number x = myNumsContra.get(0);
// does not compile, because we cannot know this is really a `Number`.
Thilo
  • 257,207
  • 101
  • 511
  • 656