File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Problem overriding hashcode and equals Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Problem overriding hashcode and equals " Watch "Problem overriding hashcode and equals " New topic

Problem overriding hashcode and equals

Eugenio Flores
Ranch Hand

Joined: Sep 13, 2007
Posts: 38
Hello, I got a class named test, and I override both equal and hash code in order to use test objects in hash data structures such as HashSet.
But it seems that both overridings are not working because I'm able to put 2 equals test objects in a HashSet. How can that be?

I have reviewed my code several time just to see if I missing something about the way this overridings are supposed to be written. But I do not see any mistake. I even compare the two test instance to see if the return true from the equal comparison, and also they return the same hash code. So the rule that says that if two objects are equals their hashcode must be equal is accomplished.
Here is my code. Does any body see a mistake?

And the output is:

equal test: true
hashcode test: true = 255
[{127 255}, {127 255}]
Christophe Verré

Joined: Nov 24, 2005
Posts: 14688

A common error when the hashCode is not spelt properly ;)

(you can make your source more readable by using the "code" button when you write a message)

[My Blog]
All roads lead to JavaRanch
Eugenio Flores
Ranch Hand

Joined: Sep 13, 2007
Posts: 38
Christophe: You are totally rigth, I what a shame for me. But thanks a lot.

And thanks for the code button tip.

Greetings from Managua.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15087

Note that the @Override annotation exists to protect you from this mistake. If you would have used it, like this:

then the compiler would have shown you an error message, because hashcode() doesn't override any method from a superclass.

(Annotations are not on the SCJP exam, but it's useful to know this anyway).

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link:
subject: Problem overriding hashcode and equals
It's not a secret anymore!