jtkSource
jtkSource

Reputation: 685

Contravariance in generics java doesnt work as expected

   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

Upvotes: 0

Views: 41

Answers (1)

Thilo
Thilo

Reputation: 262694

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`.

Upvotes: 4

Related Questions