Java: no ArrayList modifications from external classes

I am using ArrayList in one of my Java project classes. The class keeps track of whether the list has been modified and offers several public methods for adding and removing items from the list that automatically set the variable to “changed”.

So far, the list is open, because I want my list to be publicly available to everyone. But I want the class to which the list belongs to be able to modify it. Therefore, no changes from the outside classes. Is it possible? If so, how?

Typically, you probably use the getter and setter methods to control access. But even with the getter method and the list set for another private class, one could still do it getList().remove(element)and thereby change the list from the outside without the class noticing that the list was changed.

+4
source share
5 answers

Make the ArrayList field private, but get a return getter Collections.unmodifiableList(list)that provides an unmodifiable representation.

This will allow the external code to consider it as a normal list, using for each cycle, etc., but disables the modification operations. In addition, unmodifiableList returns a view in constant time.

, . Javadoc:

. "" , , UnsupportedOperationException.

+2

ArrayList , , ArrayList, getter, i i '- ArrayList.

public class Test
{
    private List<String> list = new ArrayList<String>();

    public getString (int i)
    {
        // you might want to add some validation of i here
        return list.get(i);
    }

}

getString .

, getSize(), ( ), Iterable ( ).

+1

getter:

public List getList(){
    return new ArrayList(yourPrivateList);
}
+1

:

  • , ArrayList, . , , , . . . .
  • Collections.unmodifiableList(..).
  • , : .
+1

I think your best option here is to keep it List private and add a getter method that returns a copy List, but not the copy itself List. For instance:

public class EncapsulationTest {

    private List<Object> privateList = new ArrayList<Object>();

    // Your constructors and methods to track list
    // modification here ...

    public List<Object> getList() {
        // Maybe you need a null check here
        return new ArrayList<Object>(privateList);
    }

    public void addElement(Object newElement) {
        this.privateList.add(newElement);
        // Set your 'changed' variable to true
    }

    public void removeElement(Object element) {
        this.privateList.remove(element);
        // Set your 'changed' variable to true
    }
}

If you do, you can still read the exact copy List , but you cannot change it yourself List. Well, actually you can change the returned one List, but since it is a different object, the changes will not affect your object List.

Hope this helps.

0
source

Source: https://habr.com/ru/post/1568869/


All Articles