listOf vs asList
๐งฉ List.of(...) (Java 9+)¶
From Java
๐ง Nature¶
- Immutable โ no add/remove/update at all
- Any modification โ
UnsupportedOperationException - No nulls allowed โ throws
NullPointerException
โก Behavior¶
๐ฏ When to use¶
- Fixed data (constants, configs)
- Safe sharing (no accidental modification)
- Clean, modern code
๐งฉ Arrays.asList(...)¶
From Java Arrays
๐ง Nature¶
- Fixed-size list (backed by array)
- You can update elements, but canโt change size
โก Behavior¶
โ ๏ธ 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:
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
๐ง Nature¶
- Returns a mutable list (usually
ArrayList) - No guarantee of exact implementation (but practically ArrayList)
2. Stream.toList() (Java 16+)¶
Cleaner version:
๐ง Nature¶
- Returns unmodifiable list (like
List.of) - More modern, less boilerplate
3. Arrays.asList()¶
- Fixed-size list (you already saw this one)
4. List.of()¶
- 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:
Collectionsclass 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()