Java 的 hashCode 方法是 String 方法之一,用于查找并返回用户指定字符串的哈希码。空字符串的 hashCode 值为零,本文将通过示例展示如何使用它。
哈希码背后的公式为:s[0]*31(n-1) + s[1]*31(n-2) + .. s(n-2)。其中,s[i] 是用户指定字符串的第 i 个字符,n 是字符串的长度。此 Java 编程语言中字符串 hashCode 的语法是:
public int hashCode() // It will return the integer Value as Output //In order to use in program String_Object.hashCode()
- String_Object:请指定有效的对象。
如何在 Java 中查找字符串的哈希码?
在此程序中,我们使用此方法查找用户指定字符串的 hashCode 值。
package StringFunctions;
public class HashcodeMethod {
public static void main(String[] args) {
String str = "Hi";
int a = str.hashCode();
int b = "Hello".hashCode();
int c = "Java Programming".hashCode();
int d = "hello world".hashCode();
int e = "tutorial gateway".hashCode();
System.out.println("Hashcode of the String str = " + a);
System.out.println("Hashcode of the String = " + b);
System.out.println("Hashcode of the String = " + c);
System.out.println("Hashcode of the String = " + d);
System.out.println("Hashcode of the String = " + e);
}
}

以下字符串哈希码语句将查找 str 的值。
int a = str.hashCode();
如果您观察上面的 Java 屏幕截图,该语句的输出为 2337。让我们使用标准公式找到相同的值:
HashCode = s[0]*31(n-1) + s[1]*31(n-2) + .. s(n-2)
我们都知道,位置 0 的字符是 H,位置 1 的字符是 i,长度为 2。
==> H*31(2-1) + i*31(2-2)
我们都知道,H 的 ASCII 码是 72,i 的 ASCII 码是 105。这意味着:
==> 72 * 31 + 105 * 1 (任何数的 0 次方都为 1)
==> 2232 + 105 = 2337
以下四个语句将查找句子或文本的字符串 hashCode,然后将值赋给整数变量 b、c、d 和 e。此 程序 中的最后五个 System.out.println 语句将打印 String Method 的输出。请参考 ASCII 表 查看每个字符的代码。