• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Problem overriding hashcode and equals

 
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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:

true
true
equal test: true
hashcode test: true = 255
[{127 255}, {127 255}]
 
Sheriff
Posts: 14691
16
Eclipse IDE VI Editor Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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)
 
Eugenio Flores
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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).
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic