Member-only story

List.of() vs Arrays.asList(): The Hidden Differences That Can Crash Your Code

Naveen Metta
5 min readDec 7, 2024

--

credit goes to the owner: https://taglineinfotech.com/qanda/list-of-vs-arrays-aslist-what-makes-them-different/
source: taglineinfotech.com

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…

--

--

Naveen Metta
Naveen Metta

Written by Naveen Metta

I'm a Full Stack Developer with 3+ years of experience. feel free to reach out for any help : mettanaveen701@gmail.com

No responses yet