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

    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
    Posts
    2,571
    Rep Power
    9

    Default

    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, 12:32 PM
  2. hashCode questions
    By alpdog14 in forum New To Java
    Replies: 3
    Last Post: 02-20-2010, 12:00 AM
  3. An acceptable hashcode?
    By dsym@comcast.net in forum New To Java
    Replies: 7
    Last Post: 03-29-2009, 10: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, 05:13 PM
  5. Replies: 0
    Last Post: 01-26-2008, 12:13 AM

Posting Permissions

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