How can we guarantee the immutability of an ArrayList defined in an immutable object?
3 answers
An unrecoverable list is the approach you should take. But there is a limitation, as this unmodifiable class takes a regular list and it is still modifiable.
final List<String> modifiable = new ArrayList<>();
modifiable.add("Java");
modifiable.add("is");
final List<String> unmodifiable = Collections.unmodifiableList(modifiable);
System.out.print("Before modification: " + unmodifiable);
modifiable.add("the");
modifiable.add("best");
System.out.print("After modification: " + unmodifiable);
In the above code segment, the output is unexpected as shown below.
Before change: [Java, is] After change: [Java, is, the, best]
Read this article to understand unmodifiableList pitfalls and solutions.
0
source to share
You can create an unmodifiable list from your list. The Collections class has a utility method for this.
List<String> unModifiableList=Collections.unmodifiableList(
oldList);
Once you've prepared the list inside your actual object, you can freeze it.
+2
source to share