About hashcode and equals

Source: Internet
Author: User

First, I need to explain that you can rewrite these two methods in the class we write. At this time, from the syntax perspective, they do not matter.
In the object
public native int hashCode();
public boolean equals(Object obj) {        return (this == obj);}
The two rules are in the Java set.
The following two steps are required to determine whether two objects are equal;
1. Is the hashcode value equal,
If they are not equal, then Needless to say, the two objects are definitely not equal. If the hashcode value is equal, then let's look at the second step;
2. Is the equals value equal;
Assume that the equals value is equal, then the two objects are equal;
If the equals value is not equal, the two objects are not equal;
(We can see that equals plays a final role)
Now there is a problem. Since equals plays a final role, we can directly call equals to infer whether two objects are equal in the Collection class. Why is there hashcode?

In some cases, the equals method is more complex than the equals method. We assume that the hashcode method has already indicated that the two objects are not equal, so you don't need to call equals.


Hashcode is a local method, and the returned result is a series of complex operations on the object storage location;

Equals is simply equal to the address values of the two objects;
There are several rules here.
Assuming that equals is equal, the hashcode must be equal. The address value is already equal. How can we calculate it as equal?
Assuming that the hashcode is equal, equals is not necessarily equal. 4% 3 = 1 1% 3 = 1 can be seen. Different values may obtain the same value through the same algorithm.

Code Description: first, let's take a look at the equals and hashcode strings.
public boolean equals(Object anObject) {        if (this == anObject) {            return true;        }        if (anObject instanceof String) {            String anotherString = (String) anObject;            int n = value.length;            if (n == anotherString.value.length) {                char v1[] = value;                char v2[] = anotherString.value;                int i = 0;                while (n-- != 0) {                    if (v1[i] != v2[i])                            return false;                    i++;                }                return true;            }        }        return false;    }

      /**     * Returns a hash code for this string. The hash code for a     * <code>String</code> object is computed as     * <blockquote><pre>     * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]     * </pre></blockquote>     * using <code>int</code> arithmetic, where <code>s[i]</code> is the     * <i>i</i>th character of the string, <code>n</code> is the length of     * the string, and <code>^</code> indicates exponentiation.     * (The hash value of the empty string is zero.)     *     * @return  a hash code value for this object.     */    public int hashCode() {        int h = hash;        if (h == 0 && value.length > 0) {            char val[] = value;            for (int i = 0; i < value.length; i++) {                h = 31 * h + val[i];            }            hash = h;        }        return h;    }


I have never been clear about the stare at the hashcode method.
S [0] * 31 ^ (n-1) + s [1] * 31 ^ (n-2) +... + s [n-1] // n code string length ^ code multiplication or power
For (INT I = 0; I <value. length; I ++ ){
H = 31 * H + val [I];
}
In mathematics, what is the relationship between the two?
Then I verified why the int values returned by the two methods are the same? Not clear!

The results of the following example have already been written into the gaze.
String S1 = new string ("zhaoxudong"); string S2 = new string ("zhaoxudong"); string S3 = "zhaoxudong"; string S4 = "zhaoxudong"; system. out. println (S1 = S2); // the addresses of two new objects in S1 S2 are naturally unequal. out. println (S1 = S3); // false indicates the heap memory and the constant pool system. out. println (S3 = S4); // true is in the constant pool system. out. println ("#####"); system. out. println (s1.equals (S2); // true system. out. println (s1.hashcode (); // s1.hashcode () equals s2.hashcode () equals s3.hashcode () system. out. println (s2.hashcode (); system. out. println (s3.hashcode (); Set hashset = new hashset (); hashset. add (S1); hashset. add (S2); iterator it = hashset. iterator (); While (it. hasnext () system. out. println (it. next (); // print only one


Let's look at this.
import java.util.HashSet;import java.util.Set;import java.util.Iterator;public class hashCode{    public static void main(String[] args)    {        HashSet hs=new HashSet();        hs.add(new Student(1,"zhangsan"));        hs.add(new Student(2,"lisi"));        hs.add(new Student(3,"wangwu"));        hs.add(new Student(1,"zhangsan"));         Iterator it=hs.iterator();        while(it.hasNext())            System.out.println(it.next());      }}public class Student   {     int num;     String name;     Student(int num,String name)                {                this.num=num;                 this.name=name;                 }              public String toString()                {                    return num+":"+name;                 }   }   


Execution result
1: zhangsan
3: wangwu
1: zhangsan
2: Lisi
Two Michael Jacob?
As the hash add method first finds the hashcode method of student when adding new elements. If the result does not exist, it calls the hashcode method of the object. Both zhangsan methods are new, naturally, it is not an object, so it is added!
How to change it?
Add the following two methods to the stuend class:
public int hashCode(){            return num*name.hashCode();}public boolean equals(Object o){            Student s=(Student)o;            return num==s.num && name.equals(s.name);} 


However, you must remember that if equals is equal, the hashcode must be equal, so do not write the two methods in disorder!

After the change, there will be only one zhangsan.


Exam Materials

Http://www.iteye.com/topic/257191

About hashcode and equals

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.