Java---hashcode () and Equals ()

Source: Internet
Author: User

1.hashCode () and Equals () API

hashcode () and equals() are all from the God Class Object, and all classes will have these two methods, when specific, to replicate them.

They are used for comparison purposes in the same class, especially if the objects in the container are stored in the same category as set to determine whether the object being placed is duplicated.

The following is an introduction to the API:

Booleanequals (Object obj): Compares whether two objects                                                                                                      

The Equals method implements an equivalence relationship on a non-null object reference :

reflexivity : For any non-null reference value x, X.equals (x) should return true.
symmetry : x.equals (y) should return true for any non-null reference value x and Y, 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) returns True, then X.equals (z) should return true.
consistency : For any non-null reference value x and Y, multiple calls to X.equals (Y) always return TRUE or always return false, provided that the information used in the Equals comparison on the object has not been modified.

X,x.equals (NULL) should return FALSE for any non-null reference value.

The Equals method of the object class implements the most differentiated equality relationship on the object, that is, for any non-null reference value x and Y, this method returns True if and only if X and Y refer to the same object (x = = Y has a value of true).

Note: When this 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.

inthashcode (): Returns the hash code value of an object 。                                                                                                                                  

This method is supported to improve the performance of the hash table (for example, the hash table provided by java.util.Hashtable).

The general agreement of Hashcode is:

During Java application execution, when the Hashcode method is called multiple times on the same object, the same integer must be returned consistently, provided that the information used to compare the object to equals is not modified.

The integer does not need to be consistent from one execution of an application to another execution of the same application.
If two objects are equal according to the Equals (object) method , calling the Hashcode method on each object in both objects must produce the same integer result.
If two objects are not equal according to the equals (java.lang.Object) method , the hashcode is called on any of the objects in the two objects. method does not require that a different integer result be generated . However, programmers should be aware 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 typically done by converting the object's internal address to an integer, but the JAVATM programming language does not require this implementation technique.) )

Key points:

(1) equals () equal to two objects, hashcode () must be equal, equals () unequal two objects, but does not prove that their hashcode () is not equal;

The Equals () method is not equal to two objects, and hashcode () may be equal.

(2) Hashcode (), must be able to launch equals () also unequal, hashcode () equal, Equals () may be equal, or may not vary.

(3) in the object class, the Hashcode () method is a local method that returns the address value of this object (a single object); The Equals () method in the object class compares the

is also an address value for two objects . If Equals () is equal, the two object address values are equal, and hashcode () is equal.

(4) When we rewrite the Equals method of an object, it is often necessary to rewrite its Hashcode method. General Agreement to maintain the Hashcode method

equalscomparison of () with = =

(1)' = = ' is used to compare the values of two variables (base type and object type) for equality. If the two variables are of the basic type, the direct comparison of the values is possible. If the two variables are object types, the comparison is the reference (that is, the address) of the two objects in the stack .

The object is placed in the heap, where the object's reference (address) is stored. This shows that '= = ' is the value in the comparison stack . If you want to compare the contents of objects in the heap with the same content, you should override the Equals method .
(2) The Equals method in the object class is compared with ' = = ', so equals and = = are equivalent if the Equals method is not overridden.

usually we rewrite the Equals method to have equals compare the property contents of two objects instead of comparing the object's references (addresses), because we tend to think that comparing the contents of an object is more meaningful than comparing the object's reference (address).

The role of 2.HashCode

In the data structure---hash table is a simple introduction to the principle of the hash, a word is:hash algorithm to improve the efficiency of the search element.

How do I find out if a collection contains an object?

One way is to remove each element and the object to find, using the Equals method to compare equality. If there are many elements in a collection, the efficiency is slow.

the idea of hashing algorithm : Hashcode should be similar to the use of Pinyin query Chinese characters (establish phonetic index), this way to divide the set into several storage areas, each object can calculate a hash code, you can group hashcode, each group corresponding to a storage area, Depending on the hashcode of an object, you can determine which area the object should be stored in.

An Hashcode () method is defined in the object class to return the hashcode of each Java object, and when an object is found from the set collection, theJava system first calls the object's Hashcode () method to obtain the Hashcode table of the object. Then the corresponding storage area is found according to the hashcode, and finally, each element within the storage area is compared with the Equals method of the object . This makes it not necessary to traverse all objects to improve efficiency.

The application of hashcode in Java container

For list collections, arrays, hashcode is not important, but it becomes extremely important for HashMap, HashSet, Hashtable, and so on. So in the use of HashMap, HashSet, Hashtable must pay attention to hashcode. For an object, its hashcode process is a simple implementation of the hash algorithm, and its implementation process plays a very important role in implementing the object's access process.

An object must have several properties, how to choose a property to achieve uniform hashing (hash table is also known as a hash list, it should be kept as evenly as possible, do not repeat), testing a person's design capabilities.

If we hash all the properties, this must be a bad design, because the object's Hashcode method is not called at all times, and if too many attributes participate in the hash, then the required number of operands will be greatly increased, which will severely affect the performance of the program.

If fewer zodiac participate in the hash, the diversity of the hashes weakens, resulting in a large number of hash " collisions or collisions " that, in addition to not being able to make good use of space, can affect the query efficiency of the object in some way. In fact, the two are a contradiction, the diversity of the hash will bring a decrease in performance.

3. Carbon (@Override) hashcode () and equals () chestnuts
 Public classEmployeeImplementsComparable<employee> {    PrivateString name; Private intAge ;  PublicEmployee () {Super(); }         PublicEmployee (String name,intAge ) {        Super();  This. Name =name;  This. Age =Age ; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; } @Override PublicString toString () {return"Emplooye [name=" + name + ", age=" + Age + "]"; } @Override Public inthashcode () {Final intPrime = 31; intresult = 1; Result= Prime * result +Age ; Result= Prime * result + ((name = =NULL) ? 0: Name.hashcode ()); returnresult; } @Override Public Booleanequals (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 intcompareTo (Employee o) {inttemp = This. Age-O.age; returnTemp==0? This. Name.compareto (o.name): temp; }    }

2018-01-07

Java---hashcode () and Equals ()

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.