2

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>]
implosivesilence
  • 536
  • 10
  • 24

1 Answers1

2

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;
Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63