implosivesilence :
Why somethig like line#3 is allowed and line #6 is not allowed in java?
Object[] object= new Object[100];
String[] string= new String[100];
object=string; //line #3
List<Object> objectList = new ArrayList<>();
List<String> stringList = new ArrayList<>();
objectList=stringList;// line #6 [Error: Type mismatch: cannot convert from List<String> to List<Object>]
Ravindra Ranwala :
That is because arrays are covariant and String[]
is a sub type of Object[]
, hence the assignment object = string;
is legal. But what if you do this:
object[0] = 1;
The statement compiles fine, but when you run it you get this error.
java.lang.ArrayStoreException: java.lang.Integer
On the contrary, parameterized types are invariant. So, List<String>
is neither a subtype nor a supertype of List<Object>
and your compiler starts complaining at the site of assignment objectList = stringList;
. But, if you need to make parameterized types covariant while maintaining type safety, you can use wildcards. For an instance this compiles fine.
List<?> objectList = new ArrayList<>();
List<String> stringList = new ArrayList<>();
objectList = stringList;
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=374602&siteId=1