Java--hashcode and Equal methods

Source: Internet
Author: User

Equals () reflects the specific value of an object or variable, which is the value contained within two objects-either a reference to an object or a value of a value type.

Hashcode () is a hash value that is computed by the object or variable through a hashing algorithm.

There is a hashcode method, because in the bulk of the object comparison, Hashcode is faster than equals, a lot of collections are used hashcode, such as Hashtable.

Two obj, if equals () is equal, hashcode () must be equal.

Two obj, if hashcode () is equal, Equals () is not necessarily equal (hash hash value has a conflict, although the probability is very low).


You can consider that in the collection, the rule that determines whether two objects are equal is:

The first step, if Hashcode () is equal, look at the second step, otherwise not equal;

The second step is to see if equals () is equal, and if they are equal, the two obj are equal or not equal.

1, the first Equals () and Hashcode () both methods are inherited from the object class.

Equals () is a comparison of the address values of two objects (that is, whether the comparison reference is the same).

Hashcode () is a local method, and its implementation is dependent on the local machine.

2. The Java language requirements for Equals () are as follows, and these requirements must be followed:

A symmetry: If X.equals (y) returns "true", then Y.equals (x) should also return "true".

B reflectivity: x.equals (x) must return is "true".

C analogies: If X.equals (y) returns "true" and Y.equals (z) returns "true", then Z.equals (x) should also return "true".

D Consistency: If X.equals (y) returns is "true", the return is "true" as long as the X and Y contents remain constant, no matter how many times you repeat X.equals (y).

In any case, x.equals (NULL) will always return "false", and X.equals (and X objects of different types) will always return "false".

3, Equals () equal to two objects, hashcode () must be equal;

In turn: Hashcode () range, will be able to launch equals () also ranged;

Hashcode () are equal, Equals () may be equal or unequal.


1, why to overload equal method?

Answer: Because the object's equal method defaults to a reference comparison of two objects, meaning that it points to the same memory, the address is equal, otherwise it is unequal, and if you now need to use the value inside the object to determine whether it is equal, the equal method is overloaded.

2, why overload Hashcode method?

Answer: The general place does not need to overload the hashcode, only when the class needs to put in Hashtable, HashMap, HashSet and so on hash structure's collection to overload the Hashcode, then why overloads the Hashcode? For HashMap, like HashMap is a large memory block, there are a lot of small memory block, small memory block inside is a series of objects, you can use Hashcode to find small memory block Hashcode%size (small number of memory blocks), so when equal equals, Hashcode must be equal, and if they are object objects, the hashcode and equal methods must be overloaded.

3, why equals () equal, hashcode must be equal, and hashcode equal, but does not require equals equal?

Answer: 1, because it is according to Hashcode to access small memory block, so hashcode must be equal.

2, HashMap gets an object that compares key hashcode equals and equal to true.

The reason is hashcode equal, but can equal unequal, such as objecta and OBJECTB they have attribute name, then Hashcode is the name, so hashcode, but two objects belong to different types, So equal is false.

4, why need Hashcode?

1, through the hashcode can quickly find small memory block.
2, through hashcode comparison than equal method faster, when get first compare hashcode, if hashcode different, directly return false.

The role of Hashcode ()

1.hashcode is used to find, if you learn the data structure you should know that in the search and sort this chapter has
such as in memory such as the location of
0     1      2     3     4     5     6      7    
and I have a class, this class has a field called ID, I want to store this class in one of the above 8 locations, if not hashcode and arbitrarily stored, Then, when looking for the need to go to these eight locations to find, or use a two-way algorithm.
But if you use hashcode it will make a lot more efficient.
We have a field called ID in this class, then we define our hashcode as id%8, and then we store our class in the position where we get the remainder. For example, our ID is 9, 9 except 8 of the remainder is 1, then we put the class exists 1 this position, if the ID is 13, the remainder is 5, then we put the class at 5 this position. In this way, the remainder can be found directly by ID in addition to 8 when the class is looked up.

2. But if two classes have the same hashcode what to do (we assume that the ID of the class above is not unique), such as 9 divided by 8 and 17 divided by 8 is 1, then this is not legal, the answer is: can be. So how do you judge it? At this point you need to define    equals.
that is, we first determine whether two classes are stored in a bucket by    hashcode, but there may be many classes in the bucket, so we need to go through    equals   To find the class we want in this bucket.
So. overriding Equals (), why rewrite Hashcode ()?
Think, you want to find something in a bucket, you have to find the bucket first, you do not rewrite hashcode () to find the bucket, the Light rewrite equals () What is the use of AH
3. You want to sort the class A, there are two ways to let class A implement the Comparabole structure and implement the CompareTo () method, which can be sorted by Collections.sort (list    List)
Another way: You define a class B to implement the comparator class and implement the Compare method, and then sort by Collections.sort (List list,b B)

Hashcode () is used to produce the hash, and Hashima is used to determine the storage address of the object in the hashed storage structure (which is very clear in the Java programming Idea), like the hash collection class in the Util package, is the storage structure: Hashmap,hashset, When they store objects (strictly referred to as Object references), they need to determine their address, and hashcode () is used for this purpose, and it is generally necessary to redefine it, because by default, the Hashcode method defined by the object class returns different integers for different objects. This is typically accomplished by converting the object's internal address into an integer, for example, for HashSet to determine the storage address of an object in HashSet by the hashcode () of the object being deposited, by equals () To determine if the object being deposited is duplicated, hashcode (), Equals () needs to redefine itself because Hashcode () is already said by default, and Equals () is the object reference of the comparison by default, and now you think about it, if you don't define equals (), Then the two identical objects produced by the same class can be stored in set because they are determined by equals (), so that HashSet loses his meaning and looks at the following:

ImportJava.util.*; Public classTest { Public Static voidMain (string[] args) {HashSet set=NewHashSet ();  for(inti = 0; I <= 3; i++) {Set.add (NewDemo1 (i,i));        } System.out.println (set); Set.add (NewDemo1 ());        SYSTEM.OUT.PRINTLN (set); System.out.println (Set.contains (NewDemo1 (0,0))); System.out.println (Set.add (NewDemo1 ())); System.out.println (Set.add (NewDemo1 (bis)));    SYSTEM.OUT.PRINTLN (set); }    Private Static classDemo1 {Private intvalue; Private intID;  PublicDemo1 (intValueintID) { This. Value =value;  This. id=ID; }         PublicString toString () {return"VALUE =" +value; }         Public Booleanequals (Object o) {Demo1 a=(DEMO1) o; return(A.value = = value)?true:false; }         Public inthashcode () {returnID; }    }}

You comment out the hashcode () and Equals () to compare their role can pull, the key to see the results of the comparison you can remember very clearly

If you're not quite clear, you can look at another example:

ImportJava.util.HashMap;ImportJava.util.Map; Public Final classTest { Public Static voidMain (string[] args) {Map m=NewHashMap (); M.put (NewPhoneNumber (020, 12345678), "Shellfeng"); System.out.println (M.get (NewPhoneNumber (020, 12345678))); }    Private Static classPhoneNumber {Private  ShortAreaCode; Private  Shortextension;  PublicPhoneNumber (intAreaCode,intextension) {             This. AreaCode = ( Short) AreaCode;  This. Extension = ( Short) extension; }         Public Booleanequals (Object o) {if(O = = This) {                return true; }            if(! (OinstanceofPhoneNumber)) {                return false; } phonenumber PN=(PhoneNumber) o; returnpn.extension = = Extension && Pn.areacode = =AreaCode; }         Public inthashcode () {intresult = 17; Result= PNS * result +AreaCode; Result= PNS * result +extension; returnresult; }    }}

Or that sentence: you comment off the hashcode () compare their role can pull, the key to see the results of the comparison you can remember very clearly

The Hashcode () method is used to improve the search efficiency of the map, map will be based on different hashcode () in different buckets, map in the search for an object by Hashcode () to find the corresponding bucket, and then according to Equals () method to locate the appropriate object. To properly implement the map, find the elements that must meet two conditions:
(1) when Obj1.equals (OBJ2) is true obj1.hashcode () = = Obj2.hashcode () must be true
(2) obj.equals (OBJ2) must be false when obj1.hashcode () = = Obj2.hashcode () is False

There are two types of collections (Collection) in Java, one is list, and the other is set. Do you know the difference between them? The elements within the set are ordered, the elements can be repeated, the latter elements are unordered, but the elements are not repeatable.
So here is a more serious problem: to ensure that the elements do not repeat, can two elements should be repeated based on what to judge? This is the Object.Equals method.
However, if each additional element is checked once, the number of elements that are added to the collection is much more numerous when the element is many.
That is, if there are now 1000 elements in the collection, then the 1001th element joins the collection, it calls the Equals method 1000 times. This obviously will significantly reduce efficiency.
A hashing algorithm, also known as a hashing algorithm, is a direct assignment of data to an address based on a particular algorithm. We can assume that the Hashcode method returns the physical address of the object store (which may not actually be, for example: by getting the physical address of the object and then dividing by 8 and then seeking redundancy, the remainder is the computed hash value, and we think of returning a numeric value that is not a physical address, but one that can be mapped to a physical address).
This way, when the collection is to add a new element, the Hashcode method of the element is called first, and then it can be positioned at the physical location where it should be placed. If there is no element in this position, it can be stored directly in this position without any comparison, and if there is already an element in this position, then the Equals method of calling it is compared with the new element, the same is not saved, and the other address is hashed. So there is a conflict resolution problem here. In this way, the number of actual calls to the Equals method is greatly reduced, almost only one or two times.


Java--hashcode and Equal methods

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: 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.