A. Incident Import Java.util.ArrayList; Import java.util.List; public class Test { public static void Main (string[] args) { list<string> list = new arraylist<string> (); List.add ("1"); List.add ("2"); String[] tt = (string[]) List.toarray (new string[0]); } } This code is OK, but we see string[] tt = (string[]) List.toarray (new string[0]) The parameters are very strange, but remove this parameter new String[0] but run the times wrong ... two. Root cause Analysis The study found that ToArray has two methods: Public object[] ToArray () { Object[] result = new Object[size]; System.arraycopy (elementdata, 0, result, 0, size); return result; } The ToArray method without parameters is a constructed object array and then a copy of the data, at which time the transformation will produce classcastexception, which is the root cause of the above problem. Public object[] ToArray (Object a[]) { if (A.length < size) A = (object[]) java.lang.reflect.Array.newInstance (A.getclass (). Getcomponenttype (), size); System.arraycopy (elementdata, 0, a, 0, size); if (A.length > Size) A[size] = null; return A; } The ToArray method with parameters, based on the type of the parameter array, constructs an empty array of the corresponding type, which is the same length as the size of ArrayList, although the method itself returns the result in the form of an object array. However, because the componenttype used in constructing arrays are consistent with the componenttype that need to be transformed, there is no transformation exception. three. Solutions So you can refer to the following three ways when using ToArray 1. long[] L = new Long[<total size>]; List.toarray (l); 2. long[] L = (long[]) List.toarray (new long[0]); 3. long[] A = new Long[<total size>]; Long[] L = (long[]) List.toarray (a); Four. further consideration The elements in the container have been restricted by generics, and the elements should be treated as generic types, but not in the current Java, when the direct string[] TT = (string[]) List.toarray (), run an error. Recall that the forced type conversion in Java is only for a single object, and to be lazy, it is not possible to convert the entire array into an array of another type, which is similar to the one that needs to be initialized. |