Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to implement hashCode() and equals() methods?

If I have a map and an object as map key, are the default hash and equals methods enough?

class EventInfo{

    private String name;
    private Map<String, Integer> info
 }

Then I want to create a map:

Map<EventInfo, String> map = new HashMap<EventInfo, String>();

Do I have to explicitly implement hashCode() and equals()? Thanks.

like image 449
user697911 Avatar asked Sep 26 '26 15:09

user697911


1 Answers

Yes, you do. HashMaps work by computing the hash code of the key and using that as a base point. If the hashCode function isn't overriden (by you), then it will use the memory address, and equals will be the same as ==.

If you're in Eclipse, it'll generate them for you. Click Source menu → Generate hashCode() and equals().

If you don't have Eclipse, here's some that should work. (I generated these in Eclipse, as described above.)

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((info == null) ? 0 : info.hashCode());
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj == null) {
        return false;
    }
    if (!(obj instanceof EventInfo)) {
        return false;
    }
    EventInfo other = (EventInfo) obj;
    if (info == null) {
        if (other.info != null) {
            return false;
        }
    } else if (!info.equals(other.info)) {
        return false;
    }
    if (name == null) {
        if (other.name != null) {
            return false;
        }
    } else if (!name.equals(other.name)) {
        return false;
    }
    return true;
}
like image 94
wchargin Avatar answered Sep 28 '26 07:09

wchargin