I. The role of the Hashcode method
For programming languages that contain container types, hashcode is basically involved. As in Java, the Hashcode method is primarily intended to work with hash-based collections, such as HashSet, HashMap, and Hashtable.
Why do you say that? Consider the case of how to determine if an object already exists in the collection when it is inserted into the collection. (Note: Duplicate elements in the collection are not allowed to exist)
Perhaps most people would have thought of calling the Equals method to make comparisons on a case by case basis. However, if there are already 10,000 or more data in the collection, if the Equals method is used to compare each other, efficiency must be a problem. At this point the function of the Hashcode method is reflected, when the collection to add a new object, the first call the object's Hashcode method, to get the corresponding hashcode value, In fact, in the implementation of HASHMAP will use a table to save the hashcode value of the object that has been stored in, if the table does not have the hashcode value, it can be stored directly in, no further comparison, if there is a hashcode value, The Equals method that calls it is compared with the new element, the same is not saved, and the other addresses are hashed, so there is a conflict resolution problem, so the number of actual calls to the Equals method is greatly reduced. The Hashcode method in Java is to map the object-related information (such as the object's storage address, the object's field, and so on) into a numeric value, which is called a hash, according to certain rules.
So some people would say that two objects can be judged directly according to the hashcode value of equality? It is certainly not possible, because different objects may generate the same hashcode value. Although it is not possible to determine whether two objects are equal according to the Hashcode value, two objects can be judged directly from the hashcode value, and if the hashcode value of two objects is unequal, it must be two different objects. If you want to determine whether two objects are truly equal, you must pass the Equals method.
That is to say, for two objects, if the result of calling the Equals method is true, then the hashcode value of the two objects must be equal;
If the Equals method results in False, the hashcode value of the two objects may not be different;
If the hashcode value of two objects is not equal, the result of the Equals method must be false;
If the hashcode value of two objects is equal, the result of the Equals method is unknown.
Two. Equals Method and Hashcode method
In some cases, the programmer needs to rewrite the Equals method when designing a class, such as the string class, but it is important to note that the Hashcode method must be overridden while overriding the Equals method. Why do you say that?
PackageCom.cxh.test1;ImportJava.util.HashMap;ImportJava.util.HashSet;ImportJava.util.Set; classpeople{PrivateString name; Private intAge ; PublicPeople (String name,intAge ) { This. Name =name; This. Age =Age ; } Public voidSetage (intAge ) { This. Age =Age ; } @Override Public Booleanequals (Object obj) {//TODO auto-generated Method Stub return This. Name.equals (((people) obj). Name) && This. age==((people) obj). Age; }} Public classMain { Public Static voidMain (string[] args) {people P1=NewPeople ("Jack", 12); System.out.println (P1.hashcode ()); HashMap<people, integer> HashMap =NewHashmap<people, integer>(); Hashmap.put (P1,1); System.out.println (Hashmap.get (NewPeople ("Jack", 12))); }}
Here I only rewrite the Equals method, and say if the two people object, if its name and age are equal, it is considered the same person.
The intent of this code is to think that the output of this code is "1", but in fact it outputs "null". Why is it? The reason is to rewrite the Equals method while forgetting to rewrite the Hashcode method.
Although the two objects with the same logical name and age are judged to be equal objects by overriding the Equals method (similar to the String Class), it is known by default that the Hashcode method maps the storage address of an object. It is not surprising that the output of the above code is "null". The reason is simple, P1 points to the object and
System.out.println (Hashmap.get ("Jack", 12)), the new people in this sentence ("Jack", 12) produces two objects whose storage address must be different.
The specific implementation of the Get method for HashMap:
PublicV get (Object key) {if(Key = =NULL) returnGetfornullkey (); inthash =Hash (Key.hashcode ()); for(Entry<k,v> e =table[indexfor (hash, table.length)]; E!=NULL; E=e.next) {Object k; if(E.hash = = Hash && (k = e.key) = = Key | |Key.equals (k))) returnE.value; } return NULL; }
So when HashMap get operations, because the resulting hashcdoe value is different (note that the above code may in some cases get the same hashcode value, but this probability is relatively small, Because although the storage address of two objects is different, it is possible to get the same hashcode value), so the for loop in the Get method does not execute and returns null directly.
So if you want the above code to output as "1", it is very simple to rewrite the Hashcode method so that the Equals method and the Hashcode method always logically maintain consistency.
PackageCom.cxh.test1;ImportJava.util.HashMap;ImportJava.util.HashSet;ImportJava.util.Set; classpeople{PrivateString name; Private intAge ; PublicPeople (String name,intAge ) { This. Name =name; This. Age =Age ; } Public voidSetage (intAge ) { This. Age =Age ; } @Override Public inthashcode () {//TODO auto-generated Method Stub returnName.hashcode () *37+Age ; } @Override Public Booleanequals (Object obj) {//TODO auto-generated Method Stub return This. Name.equals (((people) obj). Name) && This. age==((people) obj). Age; }} Public classMain { Public Static voidMain (string[] args) {people P1=NewPeople ("Jack", 12); System.out.println (P1.hashcode ()); HashMap<people, integer> HashMap =NewHashmap<people, integer>(); Hashmap.put (P1,1); System.out.println (Hashmap.get (NewPeople ("Jack", 12))); }}
As a result, the output will be "1".
- The Hashcode method must consistently return the same integer as long as the information used for the comparison operation of the Equals method is not modified during program execution, and the same object is called multiple times.
- If two objects are equal according to the Equals method, then the Hashcode method that calls two objects must return the same integer result.
- If two objects are unequal according to the Equals method, the Hashcode method does not necessarily return different integers.
Good understanding of the second and third articles, but the first one is often overlooked. The P495 page in the Java Programming Idea book also has a similar paragraph to the first one:
The most important factor in designing hashcode () is that whenever you call Hashcode () on the same object, you should produce the same value. If a Hashcdoe value is generated when an object is added to the HashMap with put (), and a Get () is taken out with another hashcode value, then the object cannot be obtained. So if your Hashcode method relies on variable data in the object, the user should be careful because the hashcode () method generates a different hash code when this data changes.
The Hashcode method in Java