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

Tutoriel de base Java

Contrôle de flux Java

Java tableau

Java orienté objet (I)

Java orienté objet (II)

Java orienté objet (III)

Gestion des exceptions Java

Java List

Java Queue (file d'attente)

Java Map

Java Set

Entrée et sortie Java (I/O)

Reader Java/Writer

Autres sujets de Java

Utilisation et exemple de la méthode hashCode() de String dans Java

Java String (string) methods

La méthode hashCode() de String dans Java renvoie le code hash de la chaîne.

La syntaxe de la méthode hashCode() de la chaîne de caractères est :

string.hashCode()

ici, string est un objet de la classe String.

paramètre de hashCode()

  • sans aucun paramètre

valeur de 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[1is 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 quickly store in the hash table/Retrieve the object.

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

Java String (string) methods