Difference between Arrays.asList(array) and new ArrayList(Arrays.asList(array)) in Java

There are significant differences between Arrys.asList(array) and new ArrayList(Arrays.asList(array)) 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"};

List  userList = 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, which makes the original array available as a list. Nothing is copied at all, only a single wrapper object is created. If we shuffle the list wrapper, the original array is shuffled as well. Some List operations aren’t allowed on the wrapper, like adding or removing elements from the list. We can only read or overwrite the elements.

String users[] = new String[] {"Joe", "Jennifer"};

List  userList = 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(Arrays.asList(array))

Share