Вопрос

How could I restrict the accessing (retrieving/inserting/updating/deleting) of an Arraylist and disallow changes to its values?

I had faced this question in an interview.

Это было полезно?

Решение

A 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, make it private.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top