equals() and HashCode()
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.....
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.