The difference between = = and equals in Java, the difference between equals and hashcode

Source: Internet
Author: User

In Java:

= = is an operator that compares two variables for equality.

equals, is a method of the Objec class that compares two objects for equality, and the Equals method of the Default object class is to compare the addresses of two objects, just as the result of = =. The Equals method of object is as follows:

    public boolean equals (Object obj) {        return (this = = obj);    }

Hashcode is also a method of the object class. Returns a discrete integer of type int. Used in collection class operations in order to improve query speed. (Hashmap,hashset, etc.)


With these three basic concepts, the difference is simple. There are many online, a summary of:

The data types in Java can be divided into two categories:
1. The basic data type, also known as the original data type. Byte,short,char,int,long,float,double,boolean
The comparison between them, applying the double equals sign (= =), compares their values.
2. Composite data type (Class)
When they compare with (= =), they compare the storage address in memory, so unless it is the same new object, their comparison result is true, otherwise the result is false. All classes in Java are inherited from the base class of object, and a method of equals is defined in the base class in object, and the initial behavior of this method is to compare the memory address of the object, but in some class libraries This method is overwritten, such as String,integer, In these classes, date equals has its own implementation, rather than the comparison class's storage address in heap memory.
For the equals comparison between composite data types, the comparison between them is based on the address value of the location in memory where the Equals method is not covered, because the Equals method of object is compared with the double equals sign (= =). So the result of the comparison is the same as the double equals sign (= =).


If two objects are equal according to the Equals () method, then the Hashcode method that calls either object in both objects must produce the same integer result.
If two objects are not equal according to the Equals () method, then calling the Hashcode method of any of these two objects does not necessarily produce the same integer result

As a result, the following rules are in the set operation:

When you put an object into the collection, you first determine whether the Hashcode value you want to put in the object is equal to the hashcode value of any of the elements in the collection, and if it is not equal, put the object directly into the collection. If the hashcode value is equal, then the Equals method is used to determine if any of the objects in the collection are equal, and if equals does not determine equality, the element is placed directly into the collection, otherwise it is not put.

Back to say get, HashMap also first tune Key.hashcode () count the group subscript, and then see equals if true is found, so it involves equals.



The effective Java book has two articles about equals and hashcode:

Common conventions to follow when overriding equals:
Overriding the Equals method may seem simple, but improper overwriting can result in errors, and the consequences are quite serious. "Effective Java" in the book mentioned "the easiest way to avoid such problems is not to cover the Equals method", this sentence seems very funny, in fact, it is reasonable to think, in fact, in this case, each instance of the class is only equal to itself. This is the desired result if any of the following conditions are met:
Each instance of a class is inherently unique. This is true for classes that represent active entities rather than values, such as thread. The equals implementation provided by object is the correct behavior for these classes.
Does not care if the class provides a "logical equality" test function. If random overrides equals to check whether the two random instances produce the same sequence, the designer does not think the client needs or expects such a feature. In such a case, the equals implementation obtained from object inheritance is sufficient.
The superclass has overridden equals, and the behavior inherited from the superclass is also appropriate for subclasses. Most of the set implementations inherit the equals implementation from Abstractset, and the list implementation inherits from the abstractlist equals implementation, and the map implementation inherits from the Abstractmap equals.
Class is private or package-level private, it can be determined that its Equals method is never called. In this case, there is no doubt that the Equals method should be overwritten to prevent it from being accidentally called:
@Override
public boolean equals (Object o) {
throw new Assertionerror (); Method is never called
}

When overriding the Equals method, you must abide by its general conventions. The following is the agreed content, the specification from Object [JavaSE6]
The reflexive nature. For any non-null reference value X,x.equals (x) must return True.
Symmetry. For any non-null reference value x and Y, x.equals (y) must return true if and only if Y.equals (x) returns True
Transitivity. For any non-null reference value x, Y, and Z, if X.equals (y) returns True, and Y.equals (Z) also returns True, then X.equals (z) must also return true.
Consistency. For any non-null reference value x and Y, if the information used in the object is not modified by the comparison operation of equals, multiple calls to the X.equals (y) will always return true, or return false consistently.
For any non-null reference value, x,x.equals (NULL) must return FALSE.

In combination with the above requirements, the following tips for achieving the high quality Equals method are obtained:
1. Use the = = symbol to check if the parameter is a reference to this object. If yes, returns TRUE. This is nothing more than a performance optimization, which is worth doing if the comparison operation is likely to be expensive.
2. Use the instanceof operator to check if the parameter is the correct type. If it is not, it returns false. In general, the so-called "right type" refers to the same class as the Equals method.
3. Convert the parameters to the correct type. Because the instanceof test was done before the conversion, make sure it succeeds.
4. For each "critical" field in the class, check that the field in the parameter matches the corresponding field in the object. Returns true if all of these tests are successful, otherwise false.
5. After writing completes the Equals method, check for symmetry, transitivity, and consistency.


Overwrite equals when always overwrite Hashcode
A common source of error is the failure to overwrite the Hashcode method. In each class that overrides the Equals method, you must also overwrite the Hashcode method. If you do not do this, you will violate the general conventions of Object.hashcode, resulting in the class not working properly with all hash-based collections, such as HashMap, HashSet, and Hashtable.
During application execution, the Hashcode method must consistently return the same integer if the information used for the comparison of the object's Equals method has not been modified, and the same object is called multiple times. During multiple executions of the same application, the integer returned by each execution can be inconsistent.
If two objects are equal according to the Equals () method, then the Hashcode method that calls either object in both objects must produce the same integer result.
If two objects are not equal according to the Equals () method, then calling the Hashcode method of any of these two objects does not necessarily produce the same integer result. However, programmers should know that it is possible to improve the performance of a hash table by producing distinct integer results for unequal objects.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

The difference between = = and equals in Java, the difference between equals and hashcode

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.