The following 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.
But the line of code that is commented on runs throws the following exception:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; Cannot is cast to [Ljava.lang.Integer; At My.arraylist.ArrayListTest.main (arraylisttest.java:16)
integer[] ins = (integer[]) List.toarray ();
The List.toarray () method returns the object[] array, object[] array cast to the integer[] array, the literal understanding is no problem, the compile time is OK, but the runtime throws an exception, which is why?
-
The above example confirms that the object[] array cannot be coerced into a integer[] array without doubt.
-
The integer object inherits the object, but the integer[] array does not inherit the object[] array, and the literal understanding does not seem to make sense.
-
A deeper understanding of the object[] array is not just about storing an integer object, it can also store objects such as strings and so on.
-
If an object[] array holds an integer object, also holds a string object, and a Boolean object is stored, then there is a problem when the object[] array is cast to the integer[] array. You cannot convert a string and a Boolean object to an Integer object.
Java record -44-object Array traps