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
3
  • What do you need this for? Commented Oct 11, 2017 at 16:53
  • Just my understanding. The code probably won't see the light of day. Commented Oct 11, 2017 at 16:54
  • 1
    I guess because Number is a superclass of Integer, but is not Integer. Commented Oct 11, 2017 at 16:55

1 Answer 1

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>(); 
Sign up to request clarification or add additional context in comments.

2 Comments

Then close as duplicate.
@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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.