2 回答
TA贡献1906条经验 获得超3个赞
您不能使子类LinkedHashMap不可修改,因为它会违反里氏可替换性:LinkedHashMap被记录为可变的,因此所有子类也必须是可变的。
您还有一个额外的问题,即要使地图不可修改实际上需要做很多工作:您不仅有像putand之类的明显方法remove,而且还有像clear, putAll, putIfAbsent, computeIfAbsent, 之类的东西computeIfPresent。然后你必须担心视图返回方法:entrySet,keySet,values都必须返回不可修改的视图。我确信我错过了几个也需要重写的方法,但我的观点仍然是,使可变映射不可修改并不是微不足道的。
但是,您可以拥有不可修改的 Map 实现。最简单的方法是扩展AbstractMap并委托给实际的LinkedHashMap:
public class Attributes extends AbstractMap<String, String> {
private final LinkedHashMap<String, String> delegate;
public Attributes() {
this(Collections.emptyMap());
}
public Attributes(Map<? extends String, ? extends String> map) {
this.delegate = new LinkedHashMap<>(map);
}
// Override the methods you need to, and that are required by AbstractMap.
// Details of methods to override in AbstractMap are given in Javadoc.
}
但我也会质疑你的 Attributes 类是否真的需要实现像接口一样通用的东西Map- 如果你需要这种通用性,你可以直接使用 a Map。
TA贡献1828条经验 获得超3个赞
Collections.unmodifiableMap返回 aMap<K,V>所以你必须像这样使用它:
Map<String, String> unmodifiableAttributes = Collections.unmodifiableMap( new Attributes(attributes) );
并且您无法将返回的对象转换为Attributes:
Attributes unmodifiableAttributes = (Attributes) Collections.unmodifiableMap( new Attributes(attributes) );
因为Collections.unmodifiableMap返回实例,private static UnmodifiableMap所以你会得到一个ClassCastException. 并且Attributes不是 的子类型UnmodifiableMap。
LinkedHashMap另外,我认为在您的情况下,直接使用而不是从中创建派生类会更容易,因为据我所知,功能与原始类没有什么不同。Collections.unmodifiableMap然后使用从as返回的对象Map。
添加回答
举报
