Problems with generics and subtypes in Java

First of all, since java has a strict type system, programs are checked for the correct type at compile time, and the byte code of the programs is checked when classes are loaded into the byte verifier before execution.

Although the introduction of generics has expanded the capabilities of the Java type system, there are many problems with the java subtypes in the above example:

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

        System.out.println(s);

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

+4
source share
1 answer

Arrays in Java are covariant, i.e. a String[]can be passed on to something waiting Object[]. And this is why the compiler does not stop you from inserting a boolean into a String array.

To provide covariance, but also offer runtime protection, Java engineers designed arrays so that a tag is added at compile time that marks the array with its type. Although we can add a boolean at compile time, type c String[]does not allow us to add a boolean at runtime - this is what launches ArrayStoreExceptionthat you probably encountered when you ran your code.

Java . , , Scala, .

, , , - Java .

, , .

+2

Source: https://habr.com/ru/post/1653947/


All Articles