考慮java.util.Map
接口的put
方法的規範。爲什麼Map#put指定@throws ClassCastException?
它說:
@throws ClassCastException if the class of the specified key or value
prevents it from being stored in this map
Map
是具有兩個類型參數通用接口:K
和V
分別用於鍵對象和值的對象。該put
方法簽名是:
V put(K key, V value);
在什麼情況下可能對這種方法的調用導致ClassCastException
在運行時?
我認爲,如果有是通用的,原始類型的一些混合,再而忽略了編譯器警告可能發生這種情況。因此,重讀有效的Java 2後,我仿照unsafeAdd
示例後的以下(編號23,第112):
public class MapClassCastException {
public static void main(String[] args) {
Map<Integer, String> m = new HashMap<>();
unsafePut(m);
System.out.println(m.get(1));
}
private static void unsafePut(Map m) { // beware: Raw Type
m.put("blow", "up");
m.put(new int[]{2, 4}, "xxx");
}
}
但是這個代碼不失敗,在與ClassCastException
運行,而不是它打印null
。 (當然,我忽略了編譯器警告只是爲了理解它)。
有人能證明如何Map#put
可能會拋出一個ClassCastException
在運行時? (我用JDK 1.6,1.7和1.8試了這個,他們產生了相同的結果)。
用'TreeMap'試一試。 – chrylis
啊,很酷。謝謝@chrylis。我忘了這個有用的'Map'實現! –