| Author |
Question about hashSet
|
Sammy Bill
Ranch Hand
Joined: Dec 29, 2008
Posts: 96
|
|
i was expecting this code to return 1 as i overrode equals. but it returned 2?
why is that?
Thanks
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16811
|
|
i was expecting this code to return 1 as i overrode equals. but it returned 2?
why is that?
The hashing collections require that you to obey the equal() / hashCode() contract. If you override equals, then you should also override hashCode() as well -- as you have the code written, you broke the contract.
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Ankit Garg
Saloon Keeper
Joined: Aug 03, 2008
Posts: 9191
|
|
|
hashCode method is not overridden. So equals will not get called. So answer will be 2...
|
SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
|
 |
Abhi vijay
Ranch Hand
Joined: Sep 16, 2008
Posts: 509
|
|
|
This is because you have not overridden hashCode().
|
 |
Sammy Bill
Ranch Hand
Joined: Dec 29, 2008
Posts: 96
|
|
Thanks
Got it.
|
 |
 |
|
|
subject: Question about hashSet
|
|
|