|
Hashcode (), like Equals (), is defined in object, let's take a look:
650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/71/1B/wKioL1XGqsvShSNTAAAbVHQbwxw333.jpg "title=" Sogou _ 2015-08-09_09-11-31.png "alt=" Wkiol1xgqsvshsntaaabvhqbwxw333.jpg "/>
Unfortunately, in object he is a native call, and we still look at how the hashcode in string is implemented:
650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/71/1F/wKiom1XGqXSAxWzcAACu_Bl9a64965.jpg "title=" Sogou _ 2015-08-09_09-14-19.png "alt=" Wkiom1xgqxsaxwzcaacu_bl9a64965.jpg "/>
Analysis:
First, it can be seen that once a string in the call Hashcode method, then the hash property will be assigned once, then call this hashcode method again, will directly return the hash attribute, and no longer calculated.
Second, from the Hashcode method inside the for loop can be seen, this hash value, is a composite value, is a synthesis of each character calculated.
Idea:
If 2 strings of their characters are exactly the same, then obviously their hashcode should be the same!
If 2 strings have different characters, will the hashcode be different? According to the above analysis, the hashcode is a comprehensive value, the character content is different, can be obtained exactly the same hashcode!
If Hashcode is the same, it will not come to any conclusion!
If the hashcode is different, then for string, their character content will certainly differ!
Relationship:
The comparison of the character contents of string is exactly the Equals method, so what is the relationship between equals and hashcode?
Previously, I thought that customizing a class should rewrite these 2 methods, they should be "natural pair". Not really!
The above topic, in fact, has shown that we rewrite the Equals method is to achieve 2 objects from the business perspective of the comparison, what is the hashcode do?
We know that algorithms are based on numbers, such as hash algorithms. In the map, it is clear that if key is an object, then this object should implement hash lookup and write, but he is an object ah, he should provide a number, in order to implement the hash algorithm!
In other words, hashcode is to give the object a number, this number is used in the hash of this data structure, to achieve fast positioning objects with! Hashcode to locate the linked list, we still have to use equals to compare the loop list.
That equals and hashcode actually have nothing to do with, not to be together, one is to compare the object is not business equality, one is to hash fast location and exist.
|