Catching ArrayStoreException at compile time

Consider the following Java method test ArrayList#toArray. Please note that I borrowed the code from this useful one.

public class GenericTest {
    public static void main(String [] args) {
        ArrayList<Integer> foo = new ArrayList<Integer>();
        foo.add(1);
        foo.add(2);
        foo.add(3);
        foo.add(4);
        foo.add(5);
        Integer[] bar = foo.toArray(new Integer[10]);
        System.out.println("bar.length: " + bar.length);

        for(Integer b : bar) { System.out.println(b); }

        String[] baz = foo.toArray(new String[10]);       // ArrayStoreException
        System.out.println("baz.length: " + baz.length);
    }
}

But note that when you try to put Integerin String[]will ArrayStoreException.

output:

$>javac GenericTest.java && java -cp . GenericTest
bar.length: 10
1
2
3
4
5
null
null
null
null
null
Exception in thread "main" java.lang.ArrayStoreException
        at java.lang.System.arraycopy(Native Method)
        at java.util.ArrayList.toArray(Unknown Source)
        at GenericTest.main(GenericTest.java:16)

Can this error be prevented using Java generators at compile time?

+3
source share
4 answers

ArrayStoreException exists precisely because the Java type system cannot handle this situation properly (IIRC, by the time Generics arrived, it was too late to modify arrays in the same way as collection frames).

Thus, you cannot prevent this problem at all during compilation.

, API- , .

. :

+7

List#toArray(T[]) - ,

<T> T[] toArray(T[] a);

, , <Type>, .

,

String[] baz = foo.<Integer>toArray(new String[10]); // doesn't compile

, , .

, Integer String ( ).

,

ArrayStoreException - runtime

, .

+2

Collection.toArray .

() , ArrayStoreException, :

public static <T> T[] toArray(List<? extends T> list, T[] t) {
    return list.toArray(t);
}

String[] s=toArray(new ArrayList<Integer>(), new String[0]);, , :

Object[] s=toArray(new ArrayList<Integer>(), new String[0]);

- - "String[] Object[]". Java.

0

ArrayStoreException- this is an exception at runtime, not compilation time, and is thrown at runtime, and it indicates that another type of array object is stored at this moment. Object x [] = new String [3]; x [0] = new integer (0); The only way to find it at compile time is to use the Integer > type , as shown below

foo.<Integer>toArray(new String[10]); 

The above will throw a compile-time error like The parameterized method <Integer>toArray(Integer[]) of type List<Integer> is not applicable for the arguments (String[]).

0
source

All Articles