ListToArray.java
//ArrayList generation
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("A");
arrayList.add("B");
arrayList.add("C");
String[] array = (String[])arrayList.toArray();
System.out.println("ArrayList = " + arrayList.toString());
System.out.println("Array= " + Arrays.toString(array));
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
Try to get the class to return
ListToArray.java
//ArrayList generation
//Omission
System.out.println(arrayList.toArray().getClass());
class [Ljava.lang.Object;
An Object type array is returned. .. ..
ListToArray.java
//ArrayList generation
//Omission
//0 for the number of elements in the array or arrayList.size()Put in
String[] array = arrayList.toArray(new String[arrayList.size()]);
//String[] array = arrayList.toArray(new String[0]);* Processing will be slower (described later)
System.out.println("ArrayList = " + arrayList.toString());
System.out.println("Array= " + Arrays.toString(array));
ArrayList = [A, B, C]
Array= [A, B, C]
java:java.util.ArrayList.class
public <T> T[] toArray(T[] a) {
if (a.length < size)
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
System.arraycopy(elementData, 0, a, 0, size); I was copying String [] as it was. If it is ~~ new String [0], it will enter Arrays.copyOf (3rd line) and copy the elements one by one, which will slow down the process. ~~ Updated on 2020/04/29
I tried to verify the processing time [Java] ArrayList → Should I specify the size for array conversion
Only the type specified in the conversion source ArrayList
Recommended Posts