初始化后使地图内容最终化,但不是地图本身

Make a Map content final after initialization, but not the map itself

我需要确保地图内容是最终的,它曾经被初始化:

Map<K, V> map = new HashMap<K, V>(iAnotherMap);

每次调用修改地图内容的方法(如放置、删除、替换...)都会以错误结束。

但我仍然可以执行另一个:

map = new HashMap<K, V>(iAnotherMap);

有什么办法可以实现吗?

谢谢

编辑:尝试 Collections.unmodifiableMap 方法,但有一个问题:

我要换行的class是:

public class IndexedHashMap<K, T> implements Map<K, Pair< Integer, T >>, Serializable 

下面的代码returns出错:

IndexedHashMap< K, T > mCurrent = new IndexedHashMap< K, T >(); 
IndexedHashMap< K, T > mConstantCurrent = Collections.unmodifiableMap(mCurrent);' 

类型不匹配:无法从 Map> 转换为 IndexedHashMap

对此有什么想法吗?

final 将使您的 reference 最终化,但地图对象仍可编辑。您需要使用来自 Collections

的现有 unmodifiableMap 包装器
Map<K, V> map = Collections.unmodifiableMap(new HashMap<K, V>(iAnotherMap));

或构建您自己的实现

如果你会用 Guava,那就是你想要的:

com.google.common.collect.ImmutableMap

否则,您需要自己实现 HashMap 以使其不可变。

您可以使用UnmodifiableMap。但是,如果你的需求过于具体,你应该扩展现有的 HashMap class 并做任何你想做的事情。

public class HashMap<K, V> extends java.util.HashMap<K, V> {

   @Override
    public V put(K key, V value) {
        // report error
        return null;
    }

    // similarly override other methods as you want

}