St.Antario
St.Antario

Reputation: 27435

Overriding hashCode when using HashMap, HashSet etc?

The question is in the title. I use HashMap as follows:

Map<Player, Partner> m = new HashMap<Player, Partner>();
//do some on m

Where both Player and Partner are just a POJO representing data-model.

public class Player{

    private int id;

    private String name;
    //etc, GET, SET
}

public class Partner{

    private int id;

    private String name;
    //etc, GET, SET
}

I would like to say that two objects of those classes are equivalent iff they have the same id. So, should I write hashCode something like

public int hashCode(){
    return id;
}

Is that a correct way to do that and why should I use it ever when I'm going to use HashMap or something similar?

Upvotes: 3

Views: 808

Answers (2)

mahesh
mahesh

Reputation: 1331

The objects are stored in hash buckets,Say if you have 100 objects, If 50 out of the 100 return hashcode value "123" and remaining 50 returns "124" they are stored in differet two buckets and hence reduces search time required.

While searching first aim is to find bucket in which the object belongs to, once finds the bucket then calls equls method to find the object

Rather than stroing all objects in one place (searching is difficult), hash based collections groups together objects having same hash code value, each such group is stored in a place called as hash bucket

Upvotes: 1

Eran
Eran

Reputation: 394026

Such hashCode would work. You'll also have to override equals in a consistent manner:

@Override
public boolean equals(Object other)
{
    if (!(other instanceof Player))
        return false;
    Player op = (Player) other;
    return id == op.id;
}

Upvotes: 8

Related Questions