Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: No ArrayList modifications from outside classes

I use an ArrayList in one of my Java project's classes. The class keeps track of whether the list has been changed and offers public methods to add and remove elements from the list that automatically set the variable to "changed".

So far the list is public because I want my list to be publicly readable from everywhere. But I only want the class that owns the list to be able to modify it. So no modifications from outside classes. Is that possible? If so, how?

Usually for access control you'd probably use getter and setter methods. But even with a getter method and the list set to private another class could still do getList().remove(element) and thereby modify the list from the outside without the class noticing that the list was changed.

like image 969
CGFoX Avatar asked Mar 18 '23 12:03

CGFoX


2 Answers

Make your ArrayList field private, but have your getter return Collections.unmodifiableList(list), which provides an unmodifiable view.

This will allow external code to treat it as a normal List, using for each loops and so on, but will disable modification operations. Additionally, unmodifiableList returns a view in constant time.

This is literally the exact use case it was designed for. Javadoc:

This method allows modules to provide users with "read-only" access to internal lists. Query operations on the returned list "read through" to the specified list, and attempts to modify the returned list, whether direct or via its iterator, result in an UnsupportedOperationException.

like image 180
Louis Wasserman Avatar answered Mar 20 '23 01:03

Louis Wasserman


Make your List private and add getter method:

public List getList(){
    return new ArrayList(yourPrivateList);
}
like image 37
Tkachuk_Evgen Avatar answered Mar 20 '23 02:03

Tkachuk_Evgen