Arrays.asList() vs List.of() in Java: Immutable vs Modifiable Lists

🔍 Difference between Arrays.asList() and List.of() in Java Let’s understand this with a simple example 👇 List<Integer> ls = Arrays.asList(1, 2, 3, 4, 5, 6); List<Integer> lst = List.of(1, 2, 3, 4, 5, 6); ✅ Case 1: Arrays.asList() 1️⃣ Change value using index ls.set(0, 100); Output [100, 2, 3, 4, 5, 6] 2️⃣ Try to add a new element ls.add(7); ❌ UnsupportedOperationException 3️⃣ Try to remove an element ls.remove(2); ❌ UnsupportedOperationException 🔎 Analysis Arrays.asList() returns a fixed-size list It is backed by an array ✅ You can modify elements using set() ❌ You cannot add or remove elements ✅ null values are allowed 📌 Introduced in Java 1.2 ✅ Case 2: List.of() 1️⃣ Try to change value lst.set(0, 100); ❌ UnsupportedOperationException 2️⃣ Try to add a new element lst.add(7); ❌ UnsupportedOperationException 3️⃣ Try to remove an element lst.remove(1); ❌ UnsupportedOperationException 🔎 Analysis List.of() creates a fully immutable list ❌ You cannot add, remove, or modify ❌ null values are not allowed 📌 Introduced in Java 9 ❓ Main Question: When to use which? ✅ Use List.of() When you need a read-only / immutable list, such as: List<String> roles = List.of("ADMIN", "USER", "MANAGER"); ✔ Best for constants ✔ Prevents accidental modification ✔ Cleaner & safer code Arrays.asList() allows value modification but not size change, whereas List.of() creates a completely immutable list. #Java #JavaInterview #Collections #BackendDevelopment #SpringBoot #HappyLearning #JavaLearner #JVM

To view or add a comment, sign in

Explore content categories