如何创建深度不可修改的集合? [英] How to create a deep unmodifiable collection?

查看:143
本文介绍了如何创建深度不可修改的集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常在从getter方法返回之前使收集字段不可修改:

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);
}

但如果是X,我想不出一个方便的方法以上本身就是一个清单:

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);
}

上述问题当然是客户端无法修改List列表,它可以添加/删除嵌入列表中的Y对象。

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.

有什么想法吗?

推荐答案

我能想出的最好的用途 Google集合中的转发列表。欢迎提出意见。

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));
        }
    });
}

这篇关于如何创建深度不可修改的集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆