ArrayList vs the List returned by Arrays.asList()
When you call Arrays.asList it does not return a java.util.ArrayList
. It returns a java.util.Arrays$ArrayList
which is a fixed size list backed by the original source array. In other words, it is a view for the array exposed with Java's collection-based APIs.
String[] sourceArr = {"A", "B", "C"};
List<String> list = Arrays.asList(sourceArr);
System.out.println(list); // [A, B, C]
sourceArr[2] = ""; // changing source array changes the exposed view List
System.out.println(list); //[A, B, ]
list.set(0, "Z"); // Setting an element within the size of the source array
System.out.println(Arrays.toString(sourceArr)); //[Z, B, ]
list.set(3, "Z"); // java.lang.ArrayIndexOutOfBoundsException
System.out.println(Arrays.toString(sourceArr));
list.add("X"); //java.lang.UnsupportedOperationException
list.remove("Z"); //java.lang.UnsupportedOperationException
You cannot add elements to it and you cannot remove elements from it. If you try to add or remove elements from them you will get UnsupportedOperationException
.
I'll expand my comment a little bit.
One problem that can occur if you use asList
as it wasn't different from ArrayList
object:
List<Object> list = Array.asList(array) ;
list.remove(0); // UnsupportedOperationException :(
Here you cannot remove the 0 element because asList
returns a fixed-size list backed by the specified array. So you should do something like:
List<Object> newList = new ArrayList<>(Arrays.asList(array));
in order to make the newList
modifiable.