Search code examples
javalistunmodifiable

Unmodifiable List of modifiable objects


Let's say we have got a List<List<String>> and want to make it completely unmodifiable. Simply passing it to a Collection.unmodifiableList would not suffice because the inner Lists can still be modified.

I would go with the following approach:

List<List<String>> someList;

Make it unmodifiable:

List<List<String>> tempList = new ArrayList<>();
for(List<String> strList : someList) {
    tempList.add(Collections.unmodifiableList(strList));
}
List<List<String>> safeList = Collections.unmodifiableList(tempList);

Is this approach okay?


Solution

  • This approach should work, as long as you don't keep references to the original, modifiable, lists. Such references could modify the lists wrapped by the unmodifiable lists.