I encountered this question in a test and would like to share it with you. The question is as follows: There are two string variables x and y. When if (x.equals(y) == true), do the two strings exist? Different hash code implementations, is the judgment correct? Answer: Wrong, they have the same Hash Code value. Analysis: This question mainly examines the access method of String objects. First, we must clarify what the hash Code value of the String variable is? The state of the String object stored in the memory is stored in the hash table. When different strings are generated, they will correspond to a hash code. The hash code of the string is obtained through the hashCode() method, which returns the hash of the string. The code is of type int. The hash code of a String object is calculated according to the following formula: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] Note: Use int algorithm, where s[i] is the i-th character of the string, n is the length of the string, and ^ means exponentiation. (The hash value of an empty string is 0.) The hashCode() method in String type data inherits the hashCode() method in the Object class, and its main purpose is to improve the hash table (java.util.Hashtable) performance. Optimize access efficiency. When two identical declaration strings appear, a new object instance will not be re-created, but the existing hash code will be returned and passed to the corresponding reference. Let's introduce the general agreement of HashCode, which is roughly as follows: During the execution of a Java application, when the hashCode method is called on the same object twice, the same integer must be returned consistently, provided that the information used when comparing the object equals has not been modified. This integer does not need to remain the same from one execution of an application to another execution of the same application. If two objects are equal according to the equals(Object) method, (note: this question is a typical example), then the same integer must be generated when the hashCode() method is called on each of the two objects. result. If the two objects are not equal according to the equals(java.lang.Object) method, then calling the hashCode() method on either object does not necessarily generate different integer results. However, in practical applications, generating different integer results for different objects can improve the performance of hash tables.
This article comes from the CSDN blog. Please indicate the source when reprinting: http://blog.csdn.net/ComputerHeart/archive/2009/12/18/5030719.aspx
-