I will show you how to convert an array to an ArrayList. There are pitfalls that you will definitely fall in love with, so read on to the end!
ListToArray.java
String[] array ={"A","B","C"};
List<String> list = Arrays.asList(array);
System.out.println("Array= " + Arrays.toString(array));
System.out.println("List = " + list.toString());
Array= [A, B, C]
List = [A, B, C]
did it! It's easy.
... but
ListToArray.java
//Omission
List<String> list = Arrays.asList(array);
list.add("D"); //Add D!
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at codeSample.ListToArray.main(ListToArray.java:13)
Get an error
Try to get the class to return
ListToArray.java
//Omission
List<String> list = Arrays.asList(array);
ArrayList<String> arrayList = new ArrayList<String>();
System.out.println("Regular ArrayList= " + arrayList.getClass());
System.out.println("Conversion from array= " + list.getClass());
Regular ArrayList= class java.util.ArrayList
Conversion from array= class java.util.Arrays$ArrayList
Hmm, something different!
java:java.util.Arrays.class
//Omission
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
private static class ArrayList<E> extends AbstractList<E>
implements RandomAccess, java.io.Serializable
{
private static final long serialVersionUID = -2764017481108945198L;
private final E[] a; //←←← is final!
ArrayList(E[] array) {
a = Objects.requireNonNull(array); //Reference copy (additional note)
}
@Override
public int size() {
return a.length;
}
//Omission
}
It was returning a simplified version of ArrayList defined in the inner class of the Arrays class!
java:java.util.AbstractList.class
public boolean add(E e) {
add(size(), e);
return true;
}
//Omission
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
ListToArray.java
//Omission
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(array));
arrayList.add("D");
System.out.println("Array= " + Arrays.toString(array));
System.out.println("List = " + arrayList.toString());
Create a new ArrayList area and convert it. (Addition)
Array= [A, B, C]
List = [A, B, C, D]
Arrays.asList () just converts the type, and the referenced memory area remains the same. (Addition)
Recommended Posts