immutable: List.of vs unmodifiableList vs copyOf - null handling, views vs copies, JMH wrap/copy overhead, a Guava comparison, and the record defensive-copy trap
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
=== Both reject null, same as List.of ===
|
||||
ImmutableList.of("a", null, "c") threw NullPointerException - same as List.of
|
||||
|
||||
=== Guava's builder tolerates a size that grows past what you declared; List.of has no builder ===
|
||||
ImmutableList.builder() result = [1, 2, 3, 4, 5]
|
||||
-> java.util has no equivalent builder; you either know all elements up front for List.of(...)
|
||||
or you build an ArrayList and call List.copyOf(...) at the end - this demo's RecordDemo does exactly that.
|
||||
|
||||
=== Element limit: List.of has none in practice; the old Arrays.asList(E...) varargs ceiling is long gone ===
|
||||
List.of(... 5000 elements ...).size() = 5000 (List.of(E...) switched to a varargs array long ago - the old 1-10 overloads are just JIT-friendlier for small sizes)
|
||||
|
||||
=== Guava's ImmutableList also exposes a reverse() view and asList() - conceptually close to JEP 431's reversed() ===
|
||||
built.reverse() = [5, 4, 3, 2, 1] (Guava's reverse() predates java.util's reversed() by over a decade)
|
||||
|
||||
=== Where they genuinely differ: Guava's collections are NOT in java.base, so they ship as a real dependency ===
|
||||
Adding Guava to a project to get ImmutableList today mostly buys you nothing List.of/List.copyOf
|
||||
doesn't already give you for the collection types themselves - the builder pattern above is the
|
||||
real remaining reason, plus ImmutableList/ImmutableMap/ImmutableSet having first-class equivalents
|
||||
for ImmutableMultimap, ImmutableTable and other Guava-only collection types the JDK has no analog for.
|
||||
Reference in New Issue
Block a user