Java --- hashCode () and equals (),

Source: Internet
Author: User

Java --- hashCode () and equals (),
1. hashCode () and equals () APIs

HashCode() AndEquals() All come from the god classObject,All classes have these two methods: special timing and re-writing.

They are used for comparison in the same class, especially when a Set in a container stores the same class object to determine whether the Put object is repeated.

The following is an introduction to the API:

BooleanEquals(Object obj): compare whether two objects are equal.

The equals MethodNon-empty Object ReferenceImplementation equivalence relationship on:

Self-defense: For any non-null reference value x, x. equals (x) should return true.
Symmetry: For any non-null reference values x and y, x. equals (y) returns true only when y. equals (x) returns true.
Transmission: For any non-null reference values x, y, and z, if x. equals (y) returns true and y. equals (z) returns true, then x. equals (z) should return true.
Consistency: For any non-null reference values x and y, call x multiple times. equals (y) always returns true or false, provided that the information used in the equals comparison on the object is not modified.

Returns false for any non-null reference value x, x. equals (null.

The equals method of the Object class implements the maximum possible equality relationship between objects. That is, for any non-null reference values x and y, if and only when x and y reference the same Object, this method returns true (x = y has a value of true ).

Note: When this method is overwritten, it is usually necessary to override the hashCode method to maintain the conventional protocol of the hashCode method, which declares that equal objects must have equal hash codes.

IntHashCode(): Return the hash value of the object.

This method is supported to improve the performance of hash tables (such as hash tables provided by java. util. Hashtable.

The general protocol of hashCode is:

During Java application execution, when calling the hashCode method for the same object multiple times, the same integer must be returned consistently, the premise is that the information used for equals comparison is not modified.

This integer does not need to be consistent from one execution of an application to another execution of the same application.
If the two objects are equal according to the equals (Object) method, the hashCode method must be called for each Object of the two objects to generate the same integer result.
If the two objects are not equal according to the equals (java. lang. Object) method, different integer results are not required to be generated if the hashCode method is called on any of the two objects. However, programmers should realize that generating different integer results for unequal objects can improve the performance of the hash table.

In fact, the hashCode method defined by the Object class does return different integers for different objects. (This is generally achieved by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language .)

Key points:

(1) If equals () is equal, hashcode () must be equal. If equals () is not equal, their hashcode () is not equal;

HashCode () may be equivalent to two objects whose equals () method is not equal.

(2) If hashcode () is not the same, equals () can be introduced. If hashcode () is equal, equals () may be equal or not.

(3) In the object class, the hashcode () method is a local method and the returned value isThis objectThe address value of a single object.

YesTwo objects. If equals () is equal, the address values of the two objects are equal, and hashcode () is equal.

(4) When we override the equals method of an object, it is usually necessary to override its hashCode method. To maintain the regular protocol of the hashCode Method

Comparison between equals () and =

(1)'=' Is used to compare whether the values of two variables (basic type and object type) are equal. If the two variables are of the basic type, you can directly compare the values. If the two variables are of the object type, the two objects are compared inStack reference(Address ).

Objects are placed in the heap, And the stack stores object references (addresses ). It can be seen that'= 'Is the value in the comparison Stack. To compare whether the contents of objects in the heap are the same, rewrite the equals method.
(2)The equals method in the Object class is compared with '='. Therefore, if the equals method is not rewritten, equals and = are equivalent.

We usually rewrite the equals method to make equals compare the attribute content of two objects, instead of comparing the object reference (address ), because we often think that the content of the Compare object is more meaningful than the reference (address) of the Compare object.

2. Role of HashCode

In the data structure-hash table, the principle of the hash table is briefly introduced. One sentence is:The hash algorithm improves the efficiency of searching elements.

How can I find whether an object exists in a collection?

One way is to retrieve each element and the object to be searched one by one, and use the equals method to compare whether the elements are equal. If a collection contains many elements, the efficiency is very slow.

Hash Algorithm: The HashCode should be similar to the query of Chinese characters using pinyin (create a pinyin Index). In this way, the set is divided into several storage areas. Each object can calculate a hash code and can group the HashCode, each group corresponds to a storage region. Based on the HashCode of an object, you can determine the region where the object is stored.

The Object class defines a hashCode () method to return the HashCode of each Java Object. when an Object is searched from the Set, the Java System first calls the hashCode () of the Object () method to obtain the hashCode table of the object, then find the corresponding storage region based on the hashCode, and finally obtain each element in the storage region and compare it with the equals method of the object. In this way, you do not need to traverse all objects to improve efficiency.

Application of HashCode in Java containers

HashCode is not important for List sets and arrays, but it becomes important for HashMap, HashSet, and HashTable. Therefore, you must pay attention to hashCode when using HashMap, HashSet, and HashTable. For an object, its hashCode process is a simple Hash algorithm. Its implementation process plays a very important role in implementing the object access process.

An object must have several attributes. How to Select attributes to achieve Even Hash (a hash table is also called a hash table, which must be kept as uniform and non-duplicated as possible) is a test of a person's design ability.

If we hash all the attributes, this will be a bad design, because the hashCode method of the object is not called all the time. If too many attributes are involved in the hash, the required operand time will be greatly increased, which will seriously affect the program performance.

If a small number of objects participate in the hash, the diversity of the hash will be weakened and a large number of hash columns will be generated.Conflict or collisionIn addition to making good use of space, the query efficiency of objects is also affected to some extent. In fact, the two are a contradiction, and the diversity of hash will reduce the performance.

3. query the hashCode () and equals () of (@ Override ).
public class Employee implements Comparable<Employee> {    private String name;    private int age;            public Employee() {        super();            }        public Employee(String name, int age) {        super();        this.name = name;        this.age = age;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    @Override    public String toString() {        return "Emplooye [name=" + name + ", age=" + age + "]";    }    @Override    public int hashCode() {        final int prime = 31;        int result = 1;        result = prime * result + age;        result = prime * result + ((name == null) ? 0 : name.hashCode());        return result;    }    @Override    public boolean equals(Object obj) {        if (this == obj)            return true;        if (obj == null)            return false;        if (getClass() != obj.getClass())            return false;        Employee other = (Employee) obj;        if (age != other.age)            return false;        if (name == null) {            if (other.name != null)                return false;        } else if (!name.equals(other.name))            return false;        return true;    }    @Override    public int compareTo(Employee o) {                int temp = this.age - o.age;        return temp==0? this.name.compareTo(o.name):temp;    }    }

Related Article

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.