in the program, often get a list, the program requires the corresponding assignment to an array,You can write programs like this:For Example:Long [] L = new long[list.size ()];for (int i=0;i<list.size (); i++)L[i] = (Long) list.get (i);to write these code, it seems more cumbersome,In fact list provides ToArray () method, but to use bad, there will be classcastexceptionHow exactly this is generated, and look at the code:-----------------------------------------------------------------------------------
List List = new ArrayList ();
List.add (New Long (1)); List.add (New Long (2));
List.add (New Long (3)); List.add (New Long (4));
Long[] L = (long[]) List.toarray ();
for (int i=0; i<l.length; i++)
System.out.println (L[i].longvalue ());
-----------------------------------------------------------------------------------
The red code will throw java.lang.ClassCastException. Of course, in order to read the value, you can do this code:
-----------------------------------------------------------------------------------
Object [] A = List.toarray ();
for (int i=0;i<a.length;i++)
System.out.println (((Long) a[i]). Longvalue ());
-----------------------------------------------------------------------------------
But let the array lose the type information, this is not what we want. :(
How to use it correctly:
-----------------------------------------------------------------------------------
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);
-----------------------------------------------------------------------------------
The Java SDK Doc says:
Public object[] ToArray(object[] a)
A--the array into which the elements of this list was to be stored, if it is big enough; Otherwise, a new array of the same runtime type is allocated for this purpose. If the array A is large enough, it will put the data in full, the returned array is also pointed to the array; if it's not big enough, apply An array of the same type as the argument, put the value in, and then return.Note: If you pass in a parameter of 9 size, and the list has 5 objects, then the other four are probably null,be careful when you use it.
http://blog.csdn.net/lliei/article/details/302232;
Correct use of List.toarray () (RPM)