-3

Why i am getting this warning message that cannot convert number to integer.

List<Number> list1 = null;
List<Integer> list2 = null;
list2 = list1;// warning Type mismatch: cannot convert from List<Number> to List<Integer>.
varun
  • 472
  • 4
  • 8
  • 24

3 Answers3

5

List<Integer> is not a subtype of List<Number>.

Look at : Oracle doc

enter image description here

Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
2

Java generics are invariant.

List<String> is not assignable to a reference of type List<Object>. Unlike what you would have expect from normal reference assignment going from String to Object or even from String[] to Object[] (making arrays "covariant" was a mistake). Instead, use an upper bound limit like so:

List<? extends Number> numbers = null;
List<Integer> integers = null;
numbers = integers; // <-- Okay!
Martin Andersson
  • 18,072
  • 9
  • 87
  • 115
1

Generics are a little strange in that

List<SuperType>

is not actually a supertype of

List<SubType>

e.g. List<Number> is not a supertype of List<Integer>. (i.e. Java's generics are invariant, as opposed to covariant like Java's arrays). This is because if such a relationship held you could substitute in an List<Number> for an List<Integer>, which would then allow operations that would have been illegal if you didn't make the replacement.

To be more specific, if Java's generics were covariant like arrays, you could do this:

List<Number> list = new ArrayList<Integer>();

You'd then be able to put in a Double into list because to the compiler, list is an ArrayList! As you can see, this breaks the guarantees that generics should provide (i.e. you should only be able to put Integer objects into list), so it isn't allowed.

Because of this, you can't assign a List<Number> to a List<Integer>. In fact, I don't think you'd be able to do that even if generics were covariant without casting...

awksp
  • 11,764
  • 4
  • 37
  • 44