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,18 @@
|
||||
=== LeakyOrder: a record field that LOOKS immutable but isn't ===
|
||||
leaky.items() right after construction = [widget, gadget]
|
||||
caller mutates their OWN list reference afterwards: callerList.add(...)
|
||||
leaky.items() now = [widget, gadget, SNEAKY EXTRA ITEM] <- the record's field changed too, because it's the SAME list object
|
||||
|
||||
=== LeakyOrder.items() also returns the live mutable reference - callers can mutate it directly ===
|
||||
leaky.items() after leaky.items().add(...) = [widget, gadget, SNEAKY EXTRA ITEM, MUTATED THROUGH THE ACCESSOR]
|
||||
|
||||
=== SafeOrder: List.copyOf(...) in a compact constructor closes both holes ===
|
||||
safe.items() right after construction = [widget, gadget]
|
||||
caller mutates their OWN list reference afterwards: callerList2.add(...)
|
||||
safe.items() now = [widget, gadget] <- unchanged, it's an independent copy
|
||||
|
||||
=== And the accessor's result rejects mutation too, since List.copyOf returns an immutable list ===
|
||||
safe.items().add(...) threw UnsupportedOperationException
|
||||
|
||||
=== The constructor itself still rejects null elements, same as List.of ===
|
||||
new SafeOrder(..., listContainingNull) threw NullPointerException from inside List.copyOf(...)
|
||||
Reference in New Issue
Block a user