English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Grundlegende Anleitung

Java 流程控制

Java 数组

Java 面向对象(I)

Java 面向对象(II)

Java 面向对象(III)

Java Ausnahmebehandlung

Java 列表(List)

Java Queue(队列)

Java Map集合

Java Set集合

Java 输入输出(I/O)

Java Reader/Writer

Java 其他主题

Java String hashCode() 使用方法及示例

Java String (String) Methods

Java String hashCode()方法返回字符串的哈希码。

字符串hashCode()方法的语法为:

string.hashCode()

在这里,string是String类的一个对象。

hashCode()参数

  • 不带任何参数

hashCode()返回值

  • Return the hash code of the string, which is an int value

The hash code is calculated using the following formula:

s[0]*31(n-1) + s[1]*31(n-2) + ... + s[n-1]

where

  • s[0] is the first element of the string s, s[1] is the second element, and so on.

  • n - is the length of the string

Example: Java string hashCode()

class Main {
  public static void main(String[] args) {
    String str1 = "Java";
    String str2 = "Java Programming";
    String str3 = "";
    System.out.println(str1.hashCode()); // 2301506
    System.out.println(str2.hashCode()); // 1377009627
    // hash code of empty string is 0
    System.out.println(str3.hashCode()); // 0
  }
}

The hash code is a number generated from any object (the memory address of the object), not just a string. This number is used to store quickly in a hash table/Retrieve the object.

For two strings to be equal, their hash codes must also be equal.

Java String (String) Methods