Summary of Hashcode and Equals methods in Java

Source: Internet
Author: User
Tags md5 hash

Reprint: http://www.oschina.net/question/82993_75533

Hashcode () and Equals () are defined in the object class, which is the base class for all Java classes, so all Java classes inherit both methods.

Hashcode is used primarily as set sets, and is a quick way to determine whether an object is "probably" equal to solve a large set of problems. For example, if a collection of 10,000 elements joins an element, if it is a new element, then it must be equal 10,000 times to join. So adopt Hashcode,hashcode idea is if equal, then hashcode must be equal, in turn not necessarily; so if hashcode is not equal, then must not equal, this and MD5 hash to distinguish password is a truth. Hashcode uses a 64-bit integer so that an index can be created, the new element is added, the hashcode of the new element is determined to be present, if it does not exist, it is definitely not equal, is added to the set, and if it exists, it is compared with several elements of an existing hashcode. This greatly simplifies the equal operation of the set.

Using Hashcode () and Equals ()

The Hashcode () method is used to obtain a unique integer for the given object. This integer is used to determine where the object is stored in a similar structure in Hashtable. By default, the Hashcode () method of the object class returns the number of memory addresses stored by the objects.

Overriding the default implementation

If you do not rewrite these two methods, you will hardly encounter any problems, but sometimes the program requires that we have to change the default implementation of some objects.

To take a look at this example, let's create a simple class employee

1234567891011121314151617181920212223242526272829303132 public class Employee{    private Integer id;    private String firstname;    private String lastName;    private String department;    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getFirstname() {        return firstname;    }    public void setFirstname(String firstname) {        this.firstname = firstname;    }    public String getLastName() {        return lastName;    }    public void setLastName(String lastName) {        this.lastName = lastName;    }    public String getDepartment() {        return department;    }    public void setDepartment(String department) {        this.department = department;    }}

The employee class above just has some very basic attributes and getter, setter. Now consider a situation where you need to compare two employee.

1234567891011 public class EqualsTest {    public static void main(String[] args) {        Employee e1 = new Employee();        Employee e2 = new Employee();        e1.setId(100);        e2.setId(100);        //Prints false in console        System.out.println(e1.equals(e2));    }}

There is no doubt that the above program will output false, but, in fact, the above two objects represent the passage of an employee. The real business logic wants us to return true.
To achieve this, we need to rewrite the Equals method.

12345678910111213141516 public boolean equals(Object o) {        if(o == null)        {            return false;        }        if (o == this)        {           return true;        }        if (getClass() != o.getClass())        {            return false;        }        Employee e = (Employee) o;        return (this.getId() == e.getId());}

Add this method to the class above, and Eauqlstest will output true.
So is we done? No, let's change a test method to see.

12345678910111213141516171819202122 import java.util.HashSet;import java.util.Set;public class EqualsTest{    public static void main(String[] args)    {        Employee e1 = new Employee();        Employee e2 = new Employee();        e1.setId(100);        e2.setId(100);        //Prints ‘true‘        System.out.println(e1.equals(e2));        Set<Employee> employees = new HashSet<Employee>();        employees.add(e1);        employees.add(e2);        //Prints two objects        System.out.println(employees);    }

The result of the above program output is two. If the two Employee object equals return True,set, only one object should be stored, where is the problem?
We forgot the second important method Hashcode (). As the JDK Javadoc says, overriding the Equals () method must override the Hashcode () method. We add the following method and the program will execute correctly.

(probably means that the value of 31 is a singular prime, just a default tradition.) Does not have to use 31. However, this number can be used to handle multiplication by means of displacement, and some performance optimizations are obtained. Virtual opportunities do these optimizations automatically. )

12345678 @Override public int hashCode() {    final int PRIME = 31;    int result = 1;    result = PRIME * result + getId();    return result; }

Hash hash algorithm, so that the hash table to find a record speed change O (1). Each record has its own hashcode, and the hashing algorithm places the records in the appropriate position according to Hashcode. When looking for a record, first quickly locate the record by using Hashcode. Then compare equality by equals. Without Hashcode, one by one compares, Time becomes O (N).

The Hashcode () method requires:

When the state of the object has not changed, the values returned by multiple calls must be equal
Two object equal, the value returned by the object call must be equal

The user of the Equals method is us, and the Hashcode method is the JDK (such as inserting a value into a list, which is determined in the order of code, which is not replaced by the Equals method). As a whole, equals is equal, then hashcode must be the same. Like Hashcode, equals is not necessarily the same.

If two objects = =, then must be equal, then must be hashcode equal. The default implementation is that three methods use the method of comparing addresses, that is, three are actually equivalent. Therefore, to rewrite the equal, expand the equal of the scope of the situation, then must be synchronized to expand the equal range of hashcode, in order to maintain "= = equal,equal hashcode equal" logic.

= = refers to a comparison of 2 different references to the same object, which is the same address in memory.  

Summary of Hashcode and Equals methods in Java

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.