Member-only story
List.of() vs Arrays.asList(): The Hidden Differences That Can Crash Your Code
Programming in Java, a common task is to create lists of elements. Two methods you might come across are List.of()
and Arrays.asList()
. At a quick glance, they seem to do the same thing: make a list out of the items you give them. But hidden beneath this simple task are differences that could actually break your code if you're not careful. This article will help you understand these differences and show you how to use each method safely.
What is List.of()
?
In Java, List.of()
is a method that got introduced in Java 9. It lets you quickly make a new list that cannot be changed. This means after you use List.of()
to make a list, you cannot add, remove, or replace any elements in it. It's what programmers call "immutable".
Example of List.of()
:
List<String> listOfFruits = List.of("Apple", "Banana", "Cherry");
With the code above, you have created a list of fruits that will always have those three items and nothing else.
What is Arrays.asList()
?
On the other hand, Arrays.asList()
has been around since Java 1.2. This method also helps you create a list out of items you give it. But there is a big twist – the list you get back…