得到一個Map<String, ? extends Map<String, Integer>> mapOfMaps變數。
Map<String, Integer> result = mapOfMaps.get("aaa");
有效,但是
Map<String, Integer> result = mapOfMaps.getOrDefault("aaa",Collections.emptyMap());
說
方法 getOrDefault(Object, capture#1-of ? extends Map<String,Integer>) 在型別 Map<String,capture#1-of ? extends Map<String,Integer>> 不適用于引數 (String, Map<String,Integer>)
也一樣
Map<String, Integer> result = mapOfMaps.getOrDefault("aaa",Collections.<String,Integer>emptyMap());
或者
Map<String, Integer> result = mapOfMaps.getOrDefault("aaa",(Map<String,Integer>)Collections.EMPTY_MAP);
甚至
Map<String, Integer> result = mapOfMaps.getOrDefault("aaa",new HashMap<String, Integer>());
有沒有辦法像這樣使用 getOrDefault 還是我必須使用笨拙的方式?
Map<String, Integer> result = mapOfMaps.get("aaa");
if( result == null ) {
result = Collections.emptyMap();
}
uj5u.com熱心網友回復:
您可以使用Collections.unmodifiableMap將地圖查看為Map<String, Map<String, Integer>>.
Map<String, ? extends Map<String, Integer>> mapOfMaps = new HashMap<>();
Map<String, Map<String, Integer>> view = Collections.unmodifiableMap(mapOfMaps);
Map<String, Integer> map = view.getOrDefault("foo", Collections.emptyMap());
然而,在一行中,它看起來仍然很難看,因為您需要為unmodifiableMap.
Map<String, Integer> map = Collections.<String, Map<String, Integer>>
unmodifiableMap(mapOfMaps).getOrDefault("foo", Collections.emptyMap());
解釋
您不能呼叫任何具有無界或有界extends通配符引數的方法,因為在編譯時不知道通配符的確切型別。
讓我們更簡單地看一下Map<String, ? extends Number>,您可以將其分配給
Map<String, ? extends Number> map = new HashMap<String, Integer>();
Map<String, ? extends Number> map = new HashMap<String, Double>();
但是,在呼叫 時map.getOrDefault(Object k, V defaultValue),無法defaultValue在編譯時確定型別,因為實際型別可能會在運行時更改,即使是完全相同的賦值(盡管不是同一個實體)。
// compile-time error, could require a Double or any other Number-type
Number i = map.getOrDefault("foo", (Number)Integer.MAX_VALUE);
uj5u.com熱心網友回復:
一個可能但仍然相當笨重的解決方案是一個輔助函式:
static <K1, K2, V, M extends Map<K2, V>> Map<K2, V> getOrEmpty(Map<K1, M> mapOfMaps, K1 key) {
Map<K2, V> submap = mapOfMaps.get(key);
return submap != null ? submap : Collections.emptyMap();
}
然后稱之為
Map<String, Integer> result = getOrEmpty(mapOfMaps,"aaa");
但我仍然更喜歡無需定義額外功能的解決方案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/381455.html
