Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

disable mutability in a Java List

It would be nice to turn objects of Java's List interface into an immutable equivalent at the point in time that mutation is no longer required. That is, the client can call a freeze method that makes the List immutable. The immediate benefit to me is thread-safety without the memory expense of deep copying. (Edit: People would be correct if they assume that one extra immutable copy, to be used by all threads, is affordable.)

Is there a third-party interface or class that provides such a feature?

like image 956
H2ONaCl Avatar asked Nov 18 '12 12:11

H2ONaCl


People also ask

Is list modifiable in Java?

Lists that guarantee that no change in the list will ever be visible (even if their underlying list is modified) are referred to as immutable. It is worth noting that making a list final will not make it unmodifiable or immutable. We can still add elements or remove elements from it.

Are lists mutable in Java?

If you're wondering about java. util. ArrayList - it is mutable and it is not creating another List instance on add() or remove() . If you are looking for immutable list - check Guava implementation of ImmutableList or Collections.


1 Answers

How about Collections.unmodifiableList(List list)?

like image 65
matsev Avatar answered Sep 29 '22 10:09

matsev