3 ms·
Java does have immutable collections. It's just not an explicit type. Lots of common ways to instantiate arrays (i.e. Arrays.asList) generate immutable lists
by malfist 3y ago
Java does have immutable collections. It's just not an explicit type.
Lots of common ways to instantiate arrays (i.e. Arrays.asList) generate immutable lists
- thfuran 3y agoThat's instantiating a List, not an array.
- tialaramex 3y agoAs you would expect in a vaguely modern language, Java's "List" interface is typically backed by a growable array as the type ArrayList. Only people who have no idea about caches would think List should necessarily be some sort of Linked List type. You would use Collections.unmodifiableList to make it unmodifiable.
- cowsandmilk 3y agoCollections.unmodifiableList doesn’t prevent anyone who has a reference to the original List (or the array behind it) from modifying the List. Calling that in the constructor would not help.
- thfuran 3y agoYes, ArrayLists are array-backed, but Arrays.asList instantiates a List and does not instantiate an array.
- tialaramex 3y agoAs I explained, List is an interface. You can't instantiate it, values are instances of types not interfaces. All that return type is telling you is, surprise, asList promises what you're getting implements the List interface. See if you can guess how you can implement the List interface using an Array. Still struggling, here's the one line of a typical implementation: return new Arrays.ArrayList(a);
- thfuran 3y agoYou should at least try to be correct if you're going to be so insufferable about it.
- cowsandmilk 3y agoArrays.asList doesn’t generate an immutable list, prevent writes to the array, or prevent modifying the array via the List interface. https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Arrays.html#asList(T https://docs.oracle.com/en/java/javase/17/docs/api/java.base......)