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;