我有正在处理的代码,但是在填充HashMaps的HashMap时遇到问题。声明就是这样;
HashMap<Games, HashMap<Store, Integer>> myMap = new HashMap<Games, HashMap<Store, Integer>>();
其中
Game
和Store
是单独的对象类,只有一个类变量标题。如何在HashMaps中创建对象的实例,以及如何填充两个哈希图。因为我需要在特定商店中为游戏标记一个Integer。鉴于每个商店都有不同的商店和不同的游戏。
提前致谢
编辑
游戏类
package gameStore;
public class Games {
private String title;
public Games(String inTitle){
setTitle(inTitle);
}
private String getTitle() {
return title;
}
private void setTitle(String title) {
this.title = title;
}
}
商店分类
package gameStore;
public class LocalStores {
private String nameOfStore;
public LocalStores(String inNameOfStore){
setNameOfStore(inNameOfStore);
}
private void setNameOfStore(String nameOfStore){
this.nameOfStore = nameOfStore;
}
}
最佳答案
我会做这样的事情:
void addToMap(Games games, Store store, int value) {
HashMap<Store,Integer> m = myMap.get(games);
if (m == null) {
m = new HashMap<Store,Integer>();
myMap.put(games, m);
}
m.put(store, value);
}
更新:
由于Games和Store都用作HashMap的键,因此我建议您添加hashCode和equals方法:
游戏:
public int hashCode() {
return title.hashCode();
}
public boolean equals(Object obj) {
if (!(obj instanceof Games)) {
return false;
}
Games other = (Games)obj;
return title.equals(other.title);
}
本地商店:
public int hashCode() {
return nameOfStore.hashCode();
}
public boolean equals(Object obj) {
if (!(obj instanceof LocalStores)) {
return false;
}
LocalStores other = (LocalStores)obj;
return nameOfStore.equals(other.nameOfStore);
}
现在,为了简单起见,假设输入文件的每一行包含三个由制表符分隔的字段:游戏标题,商店名称和整数值。您将阅读如下:
InputStream stream = new FileInputStream("myfile");
try {
Reader reader = new InputStreamReader(stream, "UTF-8"); // or another encoding
try {
BufferedInputStream in = new BufferedInputStream(reader);
try {
String line = in.readLine();
while (line != null) {
String[] fields = line.split("[\\t]");
if (fields.length == 3) {
addToMap(new Games(fields[0]), new LocalStores(fields[1]), Integer.parseInt(fields[2]));
}
line = in.readLine();
}
} finally {
in.close();
}
} finally {
reader.close();
}
} finally {
stream.close();
}
关于java - 填充对象的HashMap的HashMap,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9662606/