difference between equals() and hashCode()

54,084

Solution 1

The equals() and hashCode() methods prove to be very important, when objects implementing these two methods are added to collections. If implemented incorrectly it might screwed up your life.

equals() : This method checks if some other object passed to it as an argument is equal the object in which this method is invoked. It is easy to implement the equals() method incorrectly, if you do not understand the contract. Before overriding this method, following “properties” need to keep in mind -

  • Reflexive: o1.equals(o1) - which means an Object (e.g. o1) should be equal to itself
  • Symmetric: o1.equals(o2) if and only o2.equals(o1)
  • Transitive: o1.equals(o2) && o2.equals(o3) implies that o1.equals(o3) as well
  • Consistent: o1.equals(o2) returns the same as long as o1 and o2 are unmodified
  • null comparison : !o1.equals(null) - which means that any instantiable object is not equal to null. So if you pass a null as an argument to your object o1, then it should return false.
  • Hash code value: o1.equals(o2) implies o1.hashCode() == o2.hashCode() . This is very important. If you define a equals() method then you must define a hashCode() method as well. Also it means that if you have two objects that are equal then they must have the same hashCode, however the reverse is not true

From java source code

*
* @param   obj   the reference object with which to compare.
* @return  {@code true} if this object is the same as the obj
*          argument; {@code false} otherwise.
* @see     #hashCode()
* @see     java.util.HashMap
*/
public boolean equals(Object obj) {
   return (this == obj);

}

hashCode(): This method returns a hashCode() value as an Integer and is supported for the benefit of hashing based java.util.Collection classes like Hashtable, HashMap, HashSet etc. If a class overrides the equals() method, it must implement the hashCode() method as well.Before overriding this method, you need to keep in mind

  • Whenever hashCode() method is invoked on the same object more than once during an execution of a Java program, this method must consistently return the same result. The integer result need not remain consistent from one execution of the program to the next execution of the same program.
  • If two objects are equal as per the equals() method, then calling the hashCode() method in each of the two objects must return the same integer result. So, If a field is not used in equals(), then it must not be used in hashCode() method.

  • If two objects are unequal as per the equals() method, each of the two objects can return either two different integer results or same integer results (i.e. if 2 objects have the same hashCode() result does not mean that they are equal, but if two objects are equal then they must return the same hashCode() result).

As per java source code As much as is reasonably practical, the hashCode method defined by java.lang.Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer)

Solution 2

hashCode() does not return the object's reference, but a hash of the object, computed in some way. == does not compare objects using the value of hashCode() but, as you correctly say, by the value of the objects' references.

Solution 3

You can read the hashCode documentation. In a few words it says that if (obj1.equals(obj2) is true then obj1.hashCode()==obj2.hasCode() must be true to be a valid implementation.

Note that it does not mean that two different objects cannot share the same hash code. Actually, this example is a valid (but awful) implementation of the method:

class MyClass {
    public int hashCode() {return 0;}
}

Solution 4

equals() and hashCode() are different methods and hashCode method should not be used to check if two object references are same. Reason: hashCode just returns int value for an Object, even two different objects can have same hashCode integer. The value returned by hashCode() is the object's hash code, which is the object's memory address in hexadecimal. equals() checks if the two object references are same. If two objects are equal then their hashCode must be the same, but the reverse is not true.

Solution 5

.equals() compares the actual content of the string.

The "==" operator compares if the two objects are the same reference in memory. If you were to do str = str1;, then the double-equals operator would return true because they point to the same reference in memory.

hashCode() returns a hash of the object in an arbitrary manner. The value returned will always be unique as long as the method is not overridden in some way. If .equals() returns true, the hash code should be the same.

Share:
54,084
Dhivakar
Author by

Dhivakar

Java Learner

Updated on August 06, 2022

Comments

  • Dhivakar
    Dhivakar over 1 year

    I want a brief definition about the equals() , "==" and hashCode(). If i run following code means the output will be "true false 2420395 2420395". But i had understand that equals() method compares the string and "==" compares the reference. But in output the hashCcode() method prints the reference number for both strings as same then why the "==" returns "false".

        String str = "Name";
        String str1 = new String("Name");
        
        if (str.equals(str1))
            System.out.println("true");
        else
            System.out.println("false");
    
        if (str == str1)
            System.out.println("true");
        else
            System.out.println("false");
        
        System.out.println(str.hashCode());
        System.out.println(str1.hashCode());
    
  • hansvb
    hansvb almost 10 years
    computed in some way: in some way that makes sure that same "contents" ("equal" objects) end up with the same hashcode. For Strings, it is a checksum of all characters inside. You can check the details in the Javadoc for String.
  • Dhivakar
    Dhivakar almost 10 years
    As i understand that the hashcode and memory address are the two different things, how the hash codes can be same for different objects and those are not equal.
  • dgm
    dgm almost 10 years
    "As i understand that the hashcode and memory address are the two different things," --- that's true. infact it depends on how JVM is implemented. But if you see the java source code/javadoc you will get to know about that.
  • dgm
    dgm almost 10 years
    "how the hash codes can be same for different objects and those are not equal" -- can't be. if two object are not equal their hashcode should also be different