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 . to array();
for(int I = 0; I < length; i++){
System.out.println(l[i]。 long value());
}
-
The red team can throw java.lang.ClassCastException Of course, in order to read the value, it can be coded like this:
object[]a = list . to array();
for(int I = 0; I<a. Length; i++){
system . out . println((Long)a[I])。 long value());
}
-
But let the array lose the type information, which is not what we want.
Proper use:
-
1.
Long[] l = new long [<; Total size & gt];
list . to array(l);
2.
Long[]l =(Long[])list . to array(new Long[0]);
3.
Long[]a = new Long[& lt; Total size & gt];
Long[]l =(Long[])list . toarray(a);
-
The Java sdk documentation says:
Public object [] to array (object [] a) a-the array in which the elements of this list will be stored, if it is large enough; Otherwise, a new array of the same runtime type will be allocated for this. If this array A is large enough, all the data will be put in, and the returned array will also point to this array; If it is not big enough, apply for an array of the same type as the parameter, put the value in it, and then return.
Note: If the parameters you pass in are 9 sizes and there are 5 objects in the list, the other four may be empty. Pay attention when using them. If you are not careful, you will get NullPointException.
Convert the list into an array and you will know how to get the third one.