Meaningless Drivel is fun!
The moose likes Beginning Java and the fly likes hashCode!! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "hashCode!!" Watch "hashCode!!" New topic


Brian Smith
Ranch Hand

Joined: Oct 26, 2002
Posts: 232
hi folks,
why do we need to have a hashCode() method? could you provide any instance that requires a hashCode() implemented in a class?
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
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.

Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Brian Smith
Ranch Hand

Joined: Oct 26, 2002
Posts: 232
so how do you override the hashCode() method? and what it should return? could please give an example?
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
The hashCode() method must return an int. Two objects that are considered equal must return the same hashcode.

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Joel McNary

Joined: Aug 20, 2001
Posts: 1824

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 ]

Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Charles Hasegawa
Ranch Hand

Joined: May 22, 2003
Posts: 117
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) &&
return false;
public int hashCode(){
return firstName.hashCode() + lastName.hashCode();
I agree. Here's the link:
subject: hashCode!!
It's not a secret anymore!