How can we guarantee the immutability of an ArrayList defined in an immutable object?

If I define an ArrayList in Java that is private, final and only with getters. However, the user can get the ArrayList and modify the ArrayList by adding or removing elements from it. How can I avoid this?

+3


source to share


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


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


You can simply return a new List instance to your getter method with your list as a constructor argument.

0


source







All Articles