Search code examples
javacollectionsarraylistfinal

How to prevent an ArrayList to be Structually Modified?


I am mapping a Table... say Employee to an ArrayList<Employee> which is a class level variable and I will be using it in multiple places instead of hitting the Data Base each time.

I want to keep it as read only, ie. no one can add or remove an element from the ArrayList once populated.

Can someone suggest a way to achieve this?

Edit: On modification I want some kind of Exception to be thrown.

Thanks in advance


Solution

  • You can use Collections.unmodifiableList. It will pass through reads to the backing list, so any updates to the backing (original) list will affect the immutable view that other classes see.

    If you want an unmodifiable list that is not updated when the master list is updated, you'll need to call a copy constructor:

    Collections.unmodifiableList(new ArrayList<Employee>(masterList));
    

    Guava's immutable list is also an option in this case.