Week 123 — What is the difference between List.of() and Arrays.asList()?
Question of the Week #123
What is the difference between List.of() and Arrays.asList()?
2 Replies
Java provides various factory methods for creating lists and other collections including
List.of, Arrays.asList as well as List.copyOf and Collections.unmodifiableList.
The List.of method creates a new list from the elements passed as arguments. The created list is immutable.
On the other hand, Arrays.asList creates a List view from an array. Changes to the List are reflected in the array and vice-versa. Since arrays are not resizable, it is not possible to add or remove elements.
Similar to
List.of, List.copyOf creates an immutable List that is a copy of another List Since this is a copy, changing the original List doesn't modify the copy.
On the other hand, Collections.unmodifiableList creates an unmodifiable view on a List. While that view cannot be modified, changes to the backing List are propagated to the view:
📖 Sample answer from dan1st