哈希码如何在内部创建?
How hashcode create in internally?
有人告诉我如何 java 在内部创建哈希码吗?
package swain.javainterviewhub.blogspot.in;
public class JavaInterviewHub {
public static void main(String[] args) {
String str="Alex";
System.out.println(str.hashCode());
}
}
Output:2043454
密钥哈希码算法哈希码
亚历克斯 A(1) + L(12) + E(5) + X(24)=42
The hash code for a String object is computed as
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
您还可以查看源代码以获取更多信息(此处为 Oracle JDK 8u45)。
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
Java 中的哈希码生成取决于相关对象的类型。对于字符串,算法在 Java 文档 (here) 中进行了描述。
Returns a hash code for this string. The hash code for a String object is computed as
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)
有人告诉我如何 java 在内部创建哈希码吗?
package swain.javainterviewhub.blogspot.in;
public class JavaInterviewHub {
public static void main(String[] args) {
String str="Alex";
System.out.println(str.hashCode());
}
}
Output:2043454
密钥哈希码算法哈希码
亚历克斯 A(1) + L(12) + E(5) + X(24)=42
The hash code for a String object is computed as
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
您还可以查看源代码以获取更多信息(此处为 Oracle JDK 8u45)。
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
Java 中的哈希码生成取决于相关对象的类型。对于字符串,算法在 Java 文档 (here) 中进行了描述。
Returns a hash code for this string. The hash code for a String object is computed as
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)