Hacker News new | past | comments | ask | show | jobs | submit login

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




Arrays.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......)


That's instantiating a List, not an array.


As 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.


Collections.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.


Yes, ArrayLists are array-backed, but Arrays.asList instantiates a List and does not instantiate an array.


As 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);


You should at least try to be correct if you're going to be so insufferable about it.




Consider applying for YC's W25 batch! Applications are open till Nov 12.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: