Hash map with multiple keys? [duplicate]

吃可爱长大的小学妹 提交于 2019-12-23 05:09:27

问题


Can I have a hash map in Java that looks like this?

HashMap<String, String, Integer> hmap = new HashMap<String, String, Integer>()

My question is similar to this one hereQuestion

I'm a newbie to Java. So what I want to know is, what would be the best data structure to use if I need something like above, if that is not valid?


回答1:


Create a simple class holding two String objects:

public class MyKey {
    private String a;
    private String b;

    // ... accessors, mutators etc.
}

And then use it's objects as keys in your map:

HashMap<MyKey, Integer> hmap = new HashMap<>()

Later, to add a new entry:

hmap.put(new MyKey("a", "b"), 2);


来源:https://stackoverflow.com/questions/39460294/hash-map-with-multiple-keys

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!