There are the following two methods to create a List object from an existing array.
ArrayList
Arrays.asList(Array)If you use, it will be a shallow copy and you just pass the reference.
```arraylist```When using the constructor of list implementation class such as, it will be a new replication.
### Arrays.asList
Just pass the reference as a shallow copy.
```java
// Arrays.asList()Just pass a reference
String[] ary = {"a", "b", "c"};
List<String> list = Arrays.asList(ary);
// list.add("d"); // => java.lang.UnsupportedOperationException
list.set(0, "e");
System.out.println(Arrays.toString(ary)); //=> [e, b, c]The original layout has also changed.
System.out.println(list); //=> [e, b, c]
It is possible to change the element with set, but be careful because an error will occur if you change the structure of an existing array such as add.
It will be a new copy.
//Create a new one by instantiating it with an implementation class of List such as ArrayList
String[] ary2 = {"a", "b", "c"};
List<String> list2 = new ArrayList<>(Arrays.asList(ary2));
list2.add("d");
list2.set(0, "e");
System.out.println(Arrays.toString(ary2)); //=> [a, b, c]The original array is unchanged.
System.out.println(list2); //=> [e, b, c, d]
Since new ArrayList <> (array) cannot be done, it is necessary to convert it to List object once.
Recommended Posts