2 回答

TA貢獻1906條經驗 獲得超3個贊
您不能使子類LinkedHashMap
不可修改,因為它會違反里氏可替換性:LinkedHashMap
被記錄為可變的,因此所有子類也必須是可變的。
您還有一個額外的問題,即要使地圖不可修改實際上需要做很多工作:您不僅有像put
and之類的明顯方法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
。
添加回答
舉報