How to restrict access to Arraylist and prohibit change?

How can I restrict access (retrieve / insert / update / delete) of an Arraylist and prevent changes to its values?

I came across this question in an interview.

+4
source share
1 answer

The classic solution is to wrap it using Collections.unmodifiableList().

For example:

List<Integer> sourceList;
// ...
List<Integer> readOnlyList = Collections.unmodifiableList(sourceList);

This will prevent everything except reading. If you want to prevent reading, do it private.

+5
source

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


All Articles