Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hashCode!!

 
Brian Smith
Ranch Hand
Posts: 232
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi folks,
why do we need to have a hashCode() method? could you provide any instance that requires a hashCode() implemented in a class?
thanks.
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anytime you override the equals() method in a class you should also override the hashCode() method. The reason for this is because the hashCode() is used by data structures like HashMap to organize the keys. If two objects are equal() then they must return the same hashCode(). Two unequal objects may return the same hash code but two equal objects may never return different hash codes.
 
Brian Smith
Ranch Hand
Posts: 232
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so how do you override the hashCode() method? and what it should return? could please give an example?
thanks.
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The hashCode() method must return an int. Two objects that are considered equal must return the same hashcode.
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try Effective Java, Chapter 3, by Joshua Bloch (presented in pdf format here). It should answer all your questions about hashCode and why we need to override it.
HashCode information starts at page 36 (the 12th page of the document), but I also reccomend reading the preceeding pages on .equals() as well.
[ July 01, 2003: Message edited by: Joel McNary ]
 
Charles Hasegawa
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The easiest thing to do is to return the int value of whatever you used when you override the .equals
For example :
public class Person{
private String firstName;
private String lastName;
public boolean equals(Object o){
if (o instanceof Person){
Person p = (Person)o;
return p.firstName.equals(firstName) &&
p.lastName.equals(lastName);
}
return false;
}
public int hashCode(){
return firstName.hashCode() + lastName.hashCode();
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic