Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make ArrayList Read only

In Java, how can you make an ArrayList read-only (so that no one can add elements, edit, or delete elements) after initialization?

like image 316
gmhk Avatar asked Mar 10 '10 18:03

gmhk


People also ask

How do you make a collection in Java read-only?

We can make Collections object Read-Only by using unmodifiableCollection() and to make Map Read-Only we can use unmodifiableMap() method. This method accepts any of the collection objects and returns an unmodifiable view of the specified collection.

What is read-only in Java?

Defining read-only class in Java If we make a class read-only, then we can't modify the properties or data members value of the class. If we make a class read-only, then we can only read the properties or data members value of the class.


1 Answers

Pass the ArrayList into Collections.unmodifiableList(). It returns an unmodifiable view of the specified list. Only use this returned List, and never the original ArrayList.

like image 176
Mark Pope Avatar answered Oct 16 '22 17:10

Mark Pope