如何正确使用哈希地图?

2022-09-04 08:09:11
HashMap savedStuff = new HashMap();
savedStuff.put("symbol", this.symbol); //this is a string
savedStuff.put("index", this.index); //this is an int

给我警告:

HashMap is a raw type. References to generic type HashMap<K,V> should be parameterized  

答案 1
HashMap<String, Object> savedStuff = new HashMap<String, Object>();

当然,在提取元素时,您仍然必须小心使用正确的类型。


答案 2

您需要使用泛型,如下所示:

Map<String, Object> savedStuff = new HashMap<String, Object>();

推荐