Use custom object as key

suggest change

Before using your own object as a key you must override the hashCode() and equals() methods of your object.

In simple case you would have something like:

class MyKey {
    private String name;
    MyKey(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object obj) {            
        if(obj instanceof MyKey) {
            return this.name.equals(((MyKey)obj).name);
        }
        return false;
    }
    
    @Override
    public int hashCode() {
        return this.name.hashCode();
    }
}

hashCode will decide which hash bucket the key belongs to and equals will decide which object inside that hash bucket.

Without these methods, the reference of your object will be used for the comparison above, which will not work unless you use the same object reference every time.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents