Java record-44-Object array trap
Below is a very simple program, but there are unexpected traps:
public static void main(String[] args) { ArrayList list = new ArrayList(); list.add(new Integer(1)); list.add(new Integer(2)); // Integer[] ins = (Integer[])list.toArray(); Object[] ins = list.toArray(); for(int i=0;i<ins.length;i++){ System.out.println(ins[i]); } }
The above program can be executed, no problem. However, the annotated line of code throws the following exception during runtime:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer; at my.arraylist.ArrayListTest.main(ArrayListTest.java:16)
Integer[] ins = (Integer[])list.toArray();
List. the toArray () method returns an array of Object [], and the array of Object [] is forcibly converted to an Integer [] array. The literal understanding is correct and there is no problem during compilation, however, an exception is thrown during running. Why? The preceding example shows that the Object [] array cannot be forcibly converted to an Integer [] array. The Integer Object inherits the Object, but the Integer [] array does not inherit the Object [] array. The literal understanding does not seem to work. For a deeper understanding, the Object [] array can not only store Integer objects, but also objects such as strings. If an Object [] array stores Integer objects, string objects, and Boolean objects; if the Object [] array is forcibly converted to an Integer [] array, the string and Boolean objects cannot be converted to Integer objects. Next article: http://www.bkjia.com/kf/201510/447439.html