Learn from Teacher Wang (ix) The use of the Hashcode method in Java and the Equals method

Source: Internet
Author: User

Object comparisons in Java
Speaker: Wang Shaohua QQ Group No.: 483773664 Learning Objectives:

Mastering the similarities and differences of = =, Equals (), Hashcode () in Java

First, the question

Through the previous study, we know that the Java collection has three large interfaces, the list interface, the map interface, the set interface, the characteristics of the three interface is the list interface elements can be repeated, the Map interface key object can not be duplicated, the elements in the set interface can not be duplicated. So the question is, whether the repetition of the two elements is judged by what.

Twocomparison of two objects in Java(a), = =

1, in Java, compare simple type variable with "= =", as long as two simple type value is equal to return ture, otherwise return false;

2. In Java, reference types compare = =, which represents a comparison of reference addresses. When you compare reference types with "= =", the ture is returned only if the two object that applies the variable points to the same object. The implication is that the memory addresses of the two variables are required to be equal in order to return true, and each object has its own piece of memory, so it must point to the same object to return ture.

12345678910111213 public class TestDengHao {    public static void main(String[] args) {        int a = 12;        int b = 12;        System.out.println(a==b);        Integer aA = 12;        Integer bB = 12;        System.out.println(aA==bB);        Integer A = new Integer(12);        Integer B = new Integer(12);        System.out.println(A==B);    }}

The result of the above code operation is

650) this.width=650; "border=" 0 "src=" http://s3.51cto.com/wyfs02/M01/80/2B/wKioL1c6c77gIw5ZAAANIE9Jwys367.png " data_ue_src= "E:\My knowledge\temp\d4bb06f6-a6de-41dc-8920-dfde2a5c8031.png" >

A and B are two different objects (although the values of a member are equal), so the result is false.

(ii) equals

1. The Equals () method is derived from the object class, and each custom class can override this method. The Equals () method in the object class simply compares the equality of two objects by "= =", that is, by default, equals and = = have the same effect

1234 publicclass Person {    private int id;    privateString name;}
12345678 publicclass TestEquals {    public static void main(String[] args) {        Person p1 = new Person();        Person p2 = newPerson();        System.out.println("==:"+(p1==p2));        System.out.println("equals:"+p1.equals(p2));    }}

The above code runs the effect

650) this.width=650; "border=" 0 "src=" http://s3.51cto.com/wyfs02/M02/80/2E/wKiom1c6ctaidtLCAAAL3suU7V8104.png " data_ue_src= "E:\My knowledge\temp\f04b0d44-22b1-410d-96d9-306bfde72307.png" >

(c), rewrite equals

If the requirements require, as long as the ID is the same, the same person is represented. To implement this requirement, we need to rewrite the Equals method, overriding the general rules as follows

1, First Use "= =" to determine whether equal.  

2. Determine if the Equals () method parameter is null,

False if NULL, because the current object cannot be null, and if NULL, the Equals () method cannot be called, or the java.lang.NullPointerException exception is thrown.

When the argument is not NULL, if the run-time class of two objects (obtained through GetClass () is not equal, return false, otherwise continue to judge.

3. Judge whether the members of the class correspond to equal.

This requirement only requires comparison ID, so rewrite the equals code as follows

12345678910111213 @Override    public boolean equals(Object obj) {        if (this == obj)            return true;        if (obj == null)            return false;        if (getClass() != obj.getClass())            return false;        Person other = (Person) obj;        if (id != other.id)            return false;        return true;    }
12345678910 public class TestEquals {    public static void main(String[] args) {        Person p1 = new Person();        p1.setId(1);        Person p2 = new Person();        p2.setId(1);        System.out.println("==:"+(p1==p2));        System.out.println("equals:"+p1.equals(p2));    }}

The above code runs the effect

650) this.width=650; "border=" 0 "src=" http://s3.51cto.com/wyfs02/M02/80/2B/wKioL1c6c77hLwZkAAANNRvKNx4676.png " data_ue_src= "E:\My knowledge\temp\e70484f9-37f7-4d8f-81d6-a98d736a0094.png" >

(iv), Hashcode ()

Hashcode is a method in the root class Obeject and is a local method, and its implementation is dependent on the local machine. by default, Hashcode () in object returns the 32-bit JVM memory addresses of the objects. That is, if the object does not override the method, 32 of the corresponding object is returned as the JVM memory address.

12345678910 public class TestEquals {    public static void main(String[] args) {        Person p1 = new Person();        p1.setId(1);        Person p2 = new Person();        p2.setId(1);        System.out.println("p1.hashCode:"+p1.hashCode());        System.out.println("p2.hashCode:"+p2.hashCode());    }}

650) this.width=650; "border=" 0 "src=" http://s3.51cto.com/wyfs02/M02/80/2B/wKioL1c6c77gtcVXAAAOlaLPJBc145.png " data_ue_src= "E:\My knowledge\temp\cc6cbe23-fbc4-4605-81c0-31ad872b871f.png" >

(v) equals and hashcode in the class

1. The Equals method and the Hashcode method in Java are in object, so each object has these two methods.

2, Conclusion: equals () equal to two objects, hashcode () must be equal, equals () unequal two objects, but does not prove that their hashcode () is not equal.

3, Understanding: Equals equal, indicating memory address is the same, then hashcode certainly the same;

Eqauls is not equal, the memory address is not the same, and because Hashcode is machine generated, it is possible to generate conflict caused by the generation.

Iii. rules for determining whether two objects are equal in the set of Java (a)

The Java system first calls the object's Hashcode () method to get the hash table of the object, then finds the corresponding storage area based on the hash, and finally obtains each element within the storage area compared to the object with the Equals method.

The specific rules are as follows:

1, determine whether the hashcode of two objects are equal

If it is not equal, the two objects are not equal, complete

If equal, transfer to 2

2), determine whether two objects are equal by equals

If not equal, neither object is considered equal

If equal, two objects are considered equal.

Why is the two rule not to use the first one? No, because as already said, the Equals () method may also be unequal when hashcode () is equal, so it is necessary to use the 2nd rule to limit the inclusion of non-repeating elements.

(ii) Application of hashcode and EQUALS1, without rewriting these two methods
123456789101112131415161718192021 public class Person {    private int id;    private String name;    public Person(){}    public Person(int id, String name) {        this.id = id;        this.name = name;    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}
1234567891011121314 public class TestHashSet {    public static void main(String[] args) {        HashSet hs = new HashSet();        hs.add(new Person(1, "zhangsan"));        hs.add(new Person(2, "lisi"));        hs.add(new Person(3, "wangwu"));        hs.add(new Person(1, "zhangsan"));        Iterator it = hs.iterator();        while (it.hasNext()) {            Person person = (Person) it.next();            System.out.println(person.getId()+":"+person.getName());        }    }}


Run results

650) this.width=650; "border=" 0 "src=" http://s3.51cto.com/wyfs02/M00/80/2E/wKiom1c6cteCY0-cAAAQAl96aJ4439.png " data_ue_src= "E:\My knowledge\temp\87fa7ebc-e12b-4069-bdab-685b59c5ac67.png" >

Analysis: Because a different hash code value is generated when compared to a new Student (1, "Zhangsan") object established on the basis of hashcode () two times, the hashset treats him as a different object, of course, equals () The value returned by the method does not vary.

2. Rewrite these two methods

123456789101112131415161718 @Override    public int hashCode() {        // TODO Auto-generated method stub        return id*name.hashCode();    }    @Override    public boolean equals(Object obj) {         if (this == obj)                return true;            if (obj == null)                return false;            if (getClass() != obj.getClass())                return false;            Person other = (Person) obj;            if (id != other.id)                return false;            return true;    }
1234567891011121314 public class TestHashSet {    public static void main(String[] args) {        HashSet hs = new HashSet();        hs.add(new Person(1, "zhangsan"));        hs.add(new Person(2, "lisi"));        hs.add(new Person(3, "wangwu"));        hs.add(new Person(1, "zhangsan"));        Iterator it = hs.iterator();        while (it.hasNext()) {            Person person = (Person) it.next();            System.out.println(person.getId()+":"+person.getName());        }    }}

The above code runs the effect

650) this.width=650; "border=" 0 "src=" http://s3.51cto.com/wyfs02/M00/80/2E/wKiom1c6ctfyV1OwAAAhsEg8vm0379.png " data_ue_src= "E:\My knowledge\temp\3151ef78-c455-44dd-8bcb-73cd211b386e.png" >

You can see that the problem of repeating elements has been eliminated.

Iv. Summary

1, default.

= = Compares the address of the object in the JVM by default.

Hashcode default returns the storage address of the object in the JVM.

Equal compare objects, the default is to compare objects in the JVM address, with = =

2. When the Equals method is overridden, it is often necessary to override the Hashcode method to maintain the general contract of the Hashcode method, which declares that the equality object must have an equal hash code.

3, Java object comparison, in general, to rewrite hashcode and equals two methods

Five, video address

Http://edu.51cto.com/course/course_id-6028.html







From for notes (Wiz)

Learn from Teacher Wang (ix) The use of the Hashcode method in Java and the Equals method

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.