繁体   English   中英

填充对象的HashMap的HashMap

[英]Populating HashMaps of HashMap of Objects

我有正在处理的代码,但是在填充HashMaps的HashMap时遇到问题。 声明就是这样;

HashMap<Games, HashMap<Store, Integer>> myMap = new HashMap<Games, HashMap<Store,   Integer>>();

其中GameStore是单独的对象类,只有一个类变量标题。

如何在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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM