4 Replies Latest reply: Jan 17, 2013 5:11 AM by Kayaman RSS

    Hashcode generation and hashing

    AnjanN
      How can we use object as key in a collection by overriding the hashcode() and equals() method. I cannot understand the real logical picture behind that.
        • 1. Re: Hashcode generation and hashing
          Kayaman
          AnjanN wrote:
          How can we use object as key in a collection by overriding the hashcode() and equals() method.
          By making sure that equal objects return true from the equals() method (and non-equal objects return false).
          And that the generated hashcode() is the same for 2 equal objects (it can be the same for non-equal objects too).
          I cannot understand the real logical picture behind that.
          Well, perhaps you should Google around for an explanation.
          The short version is: the hashcode determines a "bucket". In the bucket, the equals() method is used to find the correct key.
          • 2. Re: Hashcode generation and hashing
            AnjanN
            it can be the same for non-equal objects too

            how can that be possible that two different objects having same hashcodes..
            • 3. Re: Hashcode generation and hashing
              Kayaman
              AnjanN wrote:
              it can be the same for non-equal objects too

              how can that be possible that two different objects having same hashcodes..
              Easily. You can implement hashcode() as "return 1;", it will just perform poorly and completely bypass the idea of hashing in the first place, but it will work.
              It's the equals() method that's used to see if 2 keys are equal.
              • 4. Re: Hashcode generation and hashing
                AnjanN
                Oops... right....good answer