如何正确使用HashMap? [英] How to correctly use HashMap?
问题描述
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
推荐答案
我不知道你是什么但是由于您提供的示例使用硬编码字符串来索引数据,因此您似乎知道要组合在一起的数据。如果是这样,那么地图可能不是一个好选择。更好的办法是把一个类从普通的数据中分出来:
I'm not sure what you're trying to do, but since the example you provided uses hard-coded strings to index the data, it seems like you know what data you want to group together. If that's the case, then a Map is probably not a good choice. The better approach would be to make a class out of the commonly grouped data:
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;
}
}
这允许您的客户端代码执行此操作: p>
This allows your client code to do this:
SavedStuff savedStuff = ...
String symbol = savedStuff.getSymbol();
而不是这样:
Map<String, Object> savedStuff = ...
String symbol = savedStuff.get("symbol");
前一个例子不太脆弱,因为您没有使用String常量索引数据。它还为您提供了一个在您的分组数据之上添加行为的地方,这使您的代码更加面向对象。
The former example is much less fragile because you're not indexing data with String constants. It also gives you a place to add behavior on top of your grouped data, which makes your code much more object oriented.
这篇关于如何正确使用HashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!