Results 1 to 2 of 2
  1. #1
    jomypgeorge is offline Member
    Join Date
    May 2010
    Rep Power

    Default 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.....

  2. #2
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Rep Power


    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

  1. hashCode() contract
    By jomypgeorge in forum New To Java
    Replies: 3
    Last Post: 01-14-2011, 11:32 AM
  2. hashCode questions
    By alpdog14 in forum New To Java
    Replies: 3
    Last Post: 02-19-2010, 11:00 PM
  3. An acceptable hashcode?
    By in forum New To Java
    Replies: 7
    Last Post: 03-29-2009, 09:04 PM
  4. Why Equals method should be over ridden in Hashcode?
    By skyineyes in forum New To Java
    Replies: 1
    Last Post: 05-26-2008, 04:13 PM
  5. Replies: 0
    Last Post: 01-25-2008, 11:13 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts