user3257654
user3257654

Reputation: 65

How to restrict accessing of an Arraylist and disallow change?

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.

Upvotes: 4

Views: 412

Answers (1)

Duncan Jones
Duncan Jones

Reputation: 69339

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.

Upvotes: 5

Related Questions