Suppose, I have a HashMap:

HashMap<MyKey, Integer> HM = new HashMap<MyKey, Integer>();

MyKey corresponds to a data object with two integer elements (and a constructor for passing two integers).

HM.put(new MyKey(1,1234), 1); // this seems to work...

but, I cannot seem to use it:

System.out.println(HM.containsKey(new MyKey(1,1234)));

I get false.

Can a HashMap have a custom data object for a Key? What am I missing? Thanks...

有帮助吗?

解决方案

You should override the equals() and hashcode() method in your MyKey class (or any other custom class for that matter that would go into a HashMap or Set). That way, when you say containsKey() (or the Set methodcontains(), or equals()), you would have explicitly specified what properties of MyKey to check for containment or equality.

You could have a simple equals() and hashCode() method like this in your MyKey class

@Override
public boolean equals(Object o) {
    boolean result = false;
    if (o instanceof MyKey) {
        MyKey mykey = (MyKey) o;
        result = (this.getX() == mykey.getX() && mykey.getY() == mykey.getY());
    }
    return result;
}

@Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + X;
        result = prime * result + Y;
        return result;
    }

(Assuming the fields in your MyKey class are X and Y)

其他提示

In your System.out, you're generating a new MyKey(). You want to check if your hashmap contains a MyKey(1,1234), not a new MyKey(1,1234).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top