Search code examples
javaunmodifiable

How to create a deep unmodifiable collection?


I often make a collection field unmodifiable before returning it from a getter method:

private List<X> _xs;
....
List<X> getXs(){
  return Collections.unmodifiableList(_xs);
}

But I can't think of a convenient way of doing that if the X above is itself a List:

private List<List<Y>> _yLists;
.....
List<List<Y>> getYLists() {
  return Collections.unmodifiableList(_yLists);
}

The problem in the above is of course that though the client cannot modify the List of lists, it can add/delete Y objects from the embedded lists.

Any thoughts?


Solution

  • The best I could come up with uses ForwardingList from Google Collections. Comments are welcome.

    private static <T> List<List<T>> unmodifiableList2(final List<List<T>> input) {
        return Collections.unmodifiableList(new ForwardingList<List<T>>() {
            @Override protected List<List<T>> delegate() {
                return Collections.unmodifiableList(input);
            }
            @Override public List<T> get(int index) {
                return Collections.unmodifiableList(delegate().get(index));
            }
        });
    }