简体   繁体   中英

difference between equals() and hashCode()

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());
}

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 (eg 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 (ie 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)

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.

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;}
}

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

equals() only compare string it's does not check reference of string

but '==' check reference and data both

in 1st case String str = "Name"; only one object is created but in

2nd case Two object is created

String str1 = new String("Name");

then reference are not same of both string that means it returns false

  1. As other said '==' compares references. But the two methods are just methods doing something which can be overridden.
  2. Every method does something. If you want to know what it exactly does and what is its meaning you need to read the documentation.
  3. You may override those methods in anyway you want. But please note that you must follow JAVA documentation for these two methods. Because they are used by other classes. For example equals() is used while you try find an object in a list and .hashCode() is used in some hashtable classes provided by JAVA class library.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM