0

Firstly, why does the first line compile while the second does not? Secondly, in the case of the second line, do both types always need to be the same i.e Integer on the left and Integer on the right. Or is it possible to have different types on the left and the right?

    List<? super Integer> nums1 = new ArrayList<Number>();  //COMPILES
    List<Integer> nums2 = new ArrayList<Number>();          //DOES NOT COMPILE
alwayscurious
  • 925
  • 1
  • 5
  • 14

1 Answers1

2

Your question is esentially a duplicate of this SO-article but in short:

? super T means "anything that is a superclass of T". Number is a superclass of Integer so this is accepted. The second line doesn't work simply because Number is not Integer. It wouldn't work vice versa, either so

ArrayList<Number> nums2 = new ArrayList<Integer>();

leads to a compile error as well. For that you can use

ArrayList<? extends Number> nums2 = new ArrayList<Integer>(); 
Lothar
  • 4,933
  • 1
  • 8
  • 26
  • Then close as duplicate. – Thorbjørn Ravn Andersen Oct 11 '17 at 17:30
  • @ThorbjørnRavnAndersen Two reasons: 1. I don't think I can single-handedly close a question and I find it a bit rude to do so. 2. Even if the linked SO-article covers the question here, I regard it more helpful to answer the question because it's easier to understand if your own code is used in the answer instead of just pointing to the general answer (which is still worth reading to get the whole details) – Lothar Oct 14 '17 at 20:28