2 回答

TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超3個(gè)贊
您不能使子類(lèi)LinkedHashMap
不可修改,因?yàn)樗鼤?huì)違反里氏可替換性:LinkedHashMap
被記錄為可變的,因此所有子類(lèi)也必須是可變的。
您還有一個(gè)額外的問(wèn)題,即要使地圖不可修改實(shí)際上需要做很多工作:您不僅有像put
and之類(lèi)的明顯方法remove
,而且還有像clear
,?putAll
,?putIfAbsent
,?computeIfAbsent
, 之類(lèi)的東西computeIfPresent
。然后你必須擔(dān)心視圖返回方法:entrySet
,keySet
,values
都必須返回不可修改的視圖。我確信我錯(cuò)過(guò)了幾個(gè)也需要重寫(xiě)的方法,但我的觀(guān)點(diǎn)仍然是,使可變映射不可修改并不是微不足道的。
但是,您可以擁有不可修改的 Map 實(shí)現(xiàn)。最簡(jiǎn)單的方法是擴(kuò)展AbstractMap
并委托給實(shí)際的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.
}
但我也會(huì)質(zhì)疑你的 Attributes 類(lèi)是否真的需要實(shí)現(xiàn)像接口一樣通用的東西Map- 如果你需要這種通用性,你可以直接使用 a Map。

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊
Collections.unmodifiableMap
返回 aMap<K,V>
所以你必須像這樣使用它:
Map<String,?String>?unmodifiableAttributes?=?Collections.unmodifiableMap(? ???????????new?Attributes(attributes) );
并且您無(wú)法將返回的對(duì)象轉(zhuǎn)換為Attributes
:
Attributes?unmodifiableAttributes?=?(Attributes)?Collections.unmodifiableMap( ????????????new?Attributes(attributes) );
因?yàn)?code>Collections.unmodifiableMap返回實(shí)例,private static UnmodifiableMap
所以你會(huì)得到一個(gè)ClassCastException
.?并且Attributes
不是 的子類(lèi)型UnmodifiableMap
。
LinkedHashMap
另外,我認(rèn)為在您的情況下,直接使用而不是從中創(chuàng)建派生類(lèi)會(huì)更容易,因?yàn)閾?jù)我所知,功能與原始類(lèi)沒(méi)有什么不同。Collections.unmodifiableMap
然后使用從as返回的對(duì)象Map
。
添加回答
舉報(bào)