Skip to content

listOf vs asList

๐Ÿงฉ List.of(...) (Java 9+)

From Java

List<String> list = List.of("A", "B", "C");

๐Ÿง  Nature

  • Immutable โ†’ no add/remove/update at all
  • Any modification โ†’ UnsupportedOperationException
  • No nulls allowed โ†’ throws NullPointerException

โšก Behavior

list.add("D");   // โŒ exception
list.

set(0,"X"); // โŒ exception

๐ŸŽฏ When to use

  • Fixed data (constants, configs)
  • Safe sharing (no accidental modification)
  • Clean, modern code

๐Ÿงฉ Arrays.asList(...)

From Java Arrays

List<String> list = Arrays.asList("A", "B", "C");

๐Ÿง  Nature

  • Fixed-size list (backed by array)
  • You can update elements, but canโ€™t change size

โšก Behavior

list.set(0, "X"); // โœ… works
list.add("D");    // โŒ exception
list.remove(1);   // โŒ exception

โš ๏ธ Hidden twist

  • Changes reflect in the underlying array
String[] arr = {"A", "B"};
List<String> list = Arrays.asList(arr);

list.set(0, "X");
System.out.println(arr[0]); // X ๐Ÿ˜ฎ

๐ŸŽฏ When to use

  • When you need a quick list view of an array
  • When element replacement is needed but size stays fixed

โš”๏ธ Side-by-side

Feature List.of() Arrays.asList()
Mutable โŒ No โš ๏ธ Partial (set only)
Add/Remove โŒ โŒ
Set (update) โŒ โœ…
Null allowed โŒ โœ…
Backed by array โŒ โœ…
Java version 9+ 1.2+

๐Ÿง  Pro tip (real-world usage)

If you want a fully mutable list, neither of these is enough:

List<String> list = new ArrayList<>(List.of("A", "B"));

Now you get:

  • add โœ…
  • remove โœ…
  • set โœ…

๐Ÿงต One-line intuition

  • List.of() โ†’ frozen statue ๐Ÿ—ฟ
  • Arrays.asList() โ†’ fixed-size rubber band ๐ŸŽฏ

1. Collectors.toList() (Streams)

From Java Stream API

List<String> list = Stream.of("A", "B", "C")
                         .collect(Collectors.toList());

๐Ÿง  Nature

  • Returns a mutable list (usually ArrayList)
  • No guarantee of exact implementation (but practically ArrayList)

2. Stream.toList() (Java 16+)

Cleaner version:

List<String> list = Stream.of("A", "B", "C")
                         .toList();

๐Ÿง  Nature

  • Returns unmodifiable list (like List.of)
  • More modern, less boilerplate

3. Arrays.asList()

List<String> list = Arrays.asList("A", "B", "C");
  • Fixed-size list (you already saw this one)

4. List.of()

List<String> list = List.of("A", "B", "C");
  • Fully immutable

โš”๏ธ Quick comparison

Method Mutable Notes
Collectors.toList() โœ… Yes Most flexible
Stream.toList() โŒ No Modern, safer
Arrays.asList() โš ๏ธ Partial Fixed size
List.of() โŒ No Fully immutable

๐ŸŽฏ Why your brain said Collections.toList()

Because:

  • Collections class exists (Collections.sort, Collections.emptyList)
  • toList() sounds logical
  • Streams + collectors blur naming

Itโ€™s like expecting Math.toSquare()โ€ฆ feels right, but Java says nope ๐Ÿ˜„


๐Ÿงต Simple memory trick

  • Stream โ†’ collect โ†’ Collectors.toList()
  • Modern shortcut โ†’ stream.toList()
  • Constants โ†’ List.of()