coder coder - 1 month ago 5
Java Question

Generics and Subtype problems in Java

First of all,since java has a strict type system ,programs are checked for type correctness at the compilation time and bytecode of programs is checked when the classes are loaded to bytecode verifier before the execution.

Though the introduction of generics has broaden the potencials of Java type system, but due to java has subtypes many problems occurs such in the above example:

String [] a ={"Hello"};
Object [] b= a;
b[0]= false;
String s=a[0];


In the above example we use that String class is a subclass of Object .
My question is what is the reason that the compiler does not produces any warning about the above program .When I try to run it (of course) throws an exception.
Also what problems/consequences the above program could have in java implementation (I mean are there any obvious problems?? ).

Nio Nio

Arrays in Java are covariant ie. a String[] can be passed to something expecting an Object[]. And this is why the compiler does not stop you sticking your boolean into the String array.

In order to provide covariance but also offer runtime protection, the Java engineers designed arrays such that a tag gets added at compile time which stamps the array with its type. Even though we can add the boolean at compile time, the type on the String[] stops us from adding the boolean at runtime - this is what triggers the ArrayStoreException you probably encountered when you ran your code.

This is a trade off in Java between having covariant arrays and catching the step of adding the wrong thing to an array. This very trade off is why some languages, like Scala, chose not have covariant arrays.

It is possible to create generic arrays but not straightforward and has some type dangers so the approaches are for specific use cases - Josh Bloch's Effective Java discusses these.

It is arguably better to use generic Lists over arrays since you can then catch issues at compile time.