Difference between Arrays.asList(array) and new ArrayList(Arrays.asList(array)) in Java
There are significant differences between Arrys.asList(array)
and new ArrayList
because the result from Arrys.asList(array)
is NOT the type of java.util.ArrayList
.
Arrys.asList(array)
creates an ArrayList of type java.util.Arrays$ArrayList which extends to java.util.AbstractList
Arrays.asList(array)
Let’s consider the following code snippet:
String users[] = new String[] {"Joe", "Jennifer"}; ListuserList = Arrays.asList(users); userList.add("Bob"); // UnsupportedOperationException occurs userList.remove("Joe"); //UnsupportedOperationException
Explanation
It takes an array users
and creates a wrapper that implements List
String users[] = new String[] {"Joe", "Jennifer"}; ListuserList = Arrays.asList(users); ArrayList userArrayList = new ArrayList<>(userList); userArrayList.add("Alex"); // Added without any exception userArrayList.remove("Joe"); // Added without any exception will not make any change in original list System.out.println(userArrayList.toString());
Explanation
When we create new ArrayList, which is a full, independent copy of the original one. The structure of this new ArrayList is completely independent of the original array. So when we shuffle it, add, remove elements etc., the original array is unchanged.
Source:
Arrays.asList(array) vs new ArrayList