Overriding hashCode when using HashMap, HashSet, etc.?
The question is in the title. I am using HashMap
like this:
Map<Player, Partner> m = new HashMap<Player, Partner>();
//do some on m
If both Player
and Partner
are only POJO
representing the 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 these classes are equivalent to iff , they have the same id
. So, should I write hashCode
something like
public int hashCode(){
return id;
}
Is this the correct way to do it and why should I ever use it when I am going to use HashMap or something similar?
source to share
Objects are stored in hash codes. Let's say if you have 100 objects. If 50 out of 100 return a hash code value of "123" and the other 50 return "124", they are stored in two separate buckets and therefore reduce the lookup time.
When looking for the first target one has to find the bucket that the object belongs to, after it finds the bucket, then calls the equls method to find the object
Instead of moving all objects in one place (finding is harder), hash-based collections are combined together with objects that have the same hash value, each such group is stored in a place called a hash bucket
source to share