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

Tutoriais Básicos de Java

Controle de fluxo do Java

Array do Java

Java orientado a objetos (I)

Java orientado a objetos (II)

Java orientado a objetos (III)

Tratamento de Exceções Java

Lista (List) do Java

Fila (Queue) do Java

Conjunto Map do Java

Conjunto Set do Java

Entrada e saída do Java (I/O)

Reader do Java/Writer

Outros tópicos do Java

Uso e exemplo do método hashCode() de String em Java

Java String (String) Methods

O método hashCode() de String em Java retorna o código hash da string.

A sintaxe do método hashCode() de String é:

string.hashCode()

Aqui, string é um objeto da classe String.

Parâmetro hashCode()

  • Sem nenhum parâmetro

Retorna o valor 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
  }
}

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

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

Java String (String) Methods