Results 1 to 2 of 2
Thread: equals() and HashCode()
- 02-10-2011, 07:31 AM #1
Member
- Join Date
- May 2010
- Posts
- 90
- Rep Power
- 0
equals() and HashCode()
hi friends,
i have a doubt about collections. i learned that collections use equals() method to check whether an object is meaningfully similar to other, and hashCode() is to arrange them in different pools.
so is equals() is enough for avoiding duplications in a collections like HashSet?
when i tried to make HashSet of my own class it allow duplication even if i add equals method in it. but when i added a hashCode() with returning just 1 it eliminate duplication.
can anyone say what is the role of hashCode() in avoid duplication here?
Thanks in advance.....
- 02-10-2011, 07:34 AM #2
Senior Member
- Join Date
- Jun 2008
- Posts
- 2,366
- Rep Power
- 7
No. Because if you override only equals, then the "hashset" (or whatever) will wind up using the hashcode the objects inherit from "Object" meaning the objects will not be in the same bucket. The API docs explicitly state that when you override one of those methods you need to (not just should) override the other to keep them consistent.
Edit: Also note that neither of those does you any good in a TreeSet, or something.
Similar Threads
-
hashCode() contract
By jomypgeorge in forum New To JavaReplies: 3Last Post: 01-14-2011, 11:32 AM -
hashCode questions
By alpdog14 in forum New To JavaReplies: 3Last Post: 02-19-2010, 11:00 PM -
An acceptable hashcode?
By dsym@comcast.net in forum New To JavaReplies: 7Last Post: 03-29-2009, 09:04 PM -
Why Equals method should be over ridden in Hashcode?
By skyineyes in forum New To JavaReplies: 1Last Post: 05-26-2008, 04:13 PM -
name clash: equals(E) in and equals(java.lang.Object)
By AdRock in forum New To JavaReplies: 0Last Post: 01-25-2008, 11:13 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks