https://stackoverflow.com/questions/7713274/java-immutable-collections
Java1-8
Collection<String> c1 = new ArrayList<String>();
c1.add("foo");
Collection<String> c2 = Collections.unmodifiableList(c1);
c1
is mutable (i.e. neither unmodifiable nor immutable).c2
is unmodifiable: it can't be changed itself, but if later on I change c1
then that change will be visible in c2
.
This is because
c2
is simply a wrapper around c1
and not really an independent copy. Guava provides the ImmutableList
interface and some implementations. Those work by actually creating a copy of the input (unless the input is an immutable collection on its own).
Regarding your second question:
The mutability/immutability of a collection does not depend on the mutability/immutability of the objects contained therein. Modifying an object contained in a collection does not count as a "modification of the collection" for this description. Of course if you need a immutable collection, you usually also want it to contain immutable objects.
Java 9:
Now java 9 has factory Methods for Immutable List, Set, Map and Map.Entry .
In Java SE 8 and earlier versions, We can use Collections class utility methods like unmodifiableXXX to create Immutable Collection objects.
However these Collections.unmodifiableXXX methods are very tedious and verbose approach. To overcome those shortcomings, Oracle corp has added couple of utility methods to List, Set and Map interfaces.
Now in java 9 :- List and Set interfaces have “of()” methods to create an empty or no-empty Immutable List or Set objects as shown below:
Empty List Example
List immutableList = List.of();
Non-Empty List Example
List immutableList = List.of("one","two","three");
No comments:
Post a Comment