• Post Reply Bookmark Topic Watch Topic
  • New Topic

Duplicates in HashSet  RSS feed

 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, can somebody tell me why seemingly equal Person object are added to HashSet. It prints Total 5 for size, I thought it should be 3. What I'm doing wrong when trying to override equals? Code is from K&B master exam, I added something to it...
 
author
Marshal
Posts: 23439
138
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's the hashCode() method -- with a capital C.

Henry
 
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

change hashcode to hashCode() with upper 'C', and it should work fine
 
Alexander Danilou
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. Amazing how simple things can elude you sometimes...
 
Java Cowboy
Sheriff
Posts: 16083
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is exactly what the @Override annotation is for. If you would have used it in your code, like this:

Then you would have gotten a compiler error, because hashcode() is not overriding a method in a superclass.

(Note, annotations are not part of the SCJP exam, but it's important to understand them, because they are being used more and more, especially in Java EE).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!