1

The following generics code doesn't compile, and I can understand why: it's to stop potentially incompatible types being added to a collection:

    List<Object> objectList = new ArrayList<Object>();
    List<String> stringList = new ArrayList<String>();
    objectList = stringList; // 'Incompatible types' compiler error
    // I understand the compilation error above
    // is to stop you adding incompatible types
    objectList.add(Integer.valueOf(1024));

However, I can do the same thing with arrays, and get no compiler error. When I run it, I get an ArrayStoreException

    Object[] objectArray = new Object[10];
    String[] stringArray = new String[10];
    objectArray = stringArray; // No compiler error on this line
    objectArray[0] = Integer.valueOf(1024); // 'java.lang.ArrayStoreException: java.lang.Integer' runtime error

Why would the compiler not stop me from doing the arrays upcast, since it goes to the trouble to stopping me doing the generics upcast?

John Farrelly
  • 7,289
  • 9
  • 42
  • 52

1 Answers1

2

As you noticed when you are trying to put incorrect type into array JVM is able to stop at runtime by throwing ArrayStoreException.

But in case of generics such mechanism is impossible (at least in if you are not using checked list) because of type erasure so since JVM can't stop you at runtime it stops you earlier at compilation time.

Pshemo
  • 122,468
  • 25
  • 185
  • 269