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
最佳答案
我不确定您要做什么,但是由于您提供的示例使用硬编码的字符串对数据建立索引,因此好像您知道要分组的数据一样。如果是这样,那么Map可能不是一个好选择。更好的方法是从通常分组的数据中创建一个类:
public class SavedStuff {
private int index;
private String symbol;
public SavedStuff(int index, String symbol) {
this.index = index;
this.symbol = symbol;
}
public int getIndex() {
return index;
}
public String getSymbol() {
return symbol;
}
}
这允许您的客户端代码执行此操作:
SavedStuff savedStuff = ...
String symbol = savedStuff.getSymbol();
而不是这样:
Map<String, Object> savedStuff = ...
String symbol = savedStuff.get("symbol");
前一个示例不那么脆弱,因为您没有使用String常量索引数据。它还为您提供了一个在分组数据之上添加行为的地方,这使您的代码更加面向对象。