In Java, how can you make an ArrayList read-only (so that no one can add elements, edit, or delete elements) after initialization?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With