Reputation: 35
List<Number> list = new ArrayList<Integer>();
I am trying to create this object but I get a compiler error, but I does not make sense because Integer extend Number, so it should work.
Upvotes: 0
Views: 89
Reputation: 84
It won't work.
Generic types in Java is that the type information for type parameters is discarded by the compiler after the compilation of code is done; therefore this type information is not available at run time. This process is called type erasure.
Either you will have to use the same datatype in both places
List<Integer> list = new ArrayList<Integer>();
Or use wildcards(?)
In wildcards you can use covariance
List<? extends Number> list = new ArrayList<Integer>();
Official Doc for reference : https://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html
Upvotes: 0
Reputation: 36
Could you give me the compiler error you are getting? I believe that you will either have to switch the List to an Integer or if the Number object is an Extension of the Integer class, you should be able to change the Integer to number and have the same features.
List<Number> list = new ArrayList<Number>();
I am not sure what you are trying to do but this has worked for me in the past, this way the ArrayList should behave just as the Number Class is defined.
Upvotes: -1
Reputation: 103018
No; generics are invariant. Meaning, only the type itself will do. That's because... it just has to be. Imagine it worked like you wanted:
List<Integer> ints = new ArrayList<Integer>();
List<Number> list = ints;
list.add(new Double(5.5));
Integer i = ints.get(0);
Go through it line by line. That code ends up trying to put a Double object in an Integer reference, which is just broken.
You can opt into covariance:
List<? extends Number> list = new ArrayList<Integer>();
works just fine. However, you can't call .add()
on such a list.
Upvotes: 5