Java - String hashCode() 方法



描述

Java 的String hashCode()方法用於獲取當前字串的雜湊碼。它返回一個整數,表示輸入物件的雜湊值。在 Java 中,雜湊碼是一個數值(整數),可用於在相等性測試中識別物件,也可作為物件的索引。

hashCode()方法不接受任何引數。在獲取當前字串的雜湊碼時,它不會丟擲任何異常。

注意 - 物件的雜湊碼值在同一應用程式的多次執行中可能會發生變化。

語法

以下是Java String hashCode()方法的語法:

public int hashCode()

引數

  • 該方法不接受任何引數。

返回值

此方法返回此物件的雜湊碼值。

空字串的雜湊碼示例

如果給定的字串是字串,則 hashCode() 方法返回零作為雜湊碼值。

在下面的程式中,我們使用空值例項化一個字串類。使用 hashCode() 方法,我們嘗試檢索當前字串的雜湊碼值。

package com.tutorialspoint;

public class HashCode {
   public static void main(String[] args) {
      
      //instantiate the string class
      String str = new String();
      System.out.println("The given string is an empty." + str);
      
      // using hashCode() method
      int str_hash_code = str.hashCode();
      System.out.println("The hash code of the current string is: " + str_hash_code);
   }
}

輸出

執行上述程式後,將產生以下結果:

The given string is an empty.
The hash code of the current string is: 0

字串的雜湊碼示例

如果給定的字串不是空字串,此方法將返回當前字串的雜湊碼值。

在下面的示例中,我們建立一個字串類的物件,其值為“TUTORIX”的大寫形式。然後,使用hashCode()方法,我們嘗試檢索當前字串的雜湊碼值。

package com.tutorialspoint;

public class HashCode {
   public static void main(String[] args) {
      
      //create an object of the string class
      String str = new String("TUTORIX");
      System.out.println("The given string is: " + str);
      
      // using hashCode() method
      int str_hash_code = str.hashCode();
      System.out.println("The hash code of the current string is: " + str_hash_code);
   }
}

輸出

以下是上述程式的輸出:

The given string is: TUTORIX
The hash code of the current string is: -245613883

單字元字串的雜湊碼示例

使用 hashCode() 方法,我們可以檢索單字元字串的雜湊碼。

在這個程式中,我們建立一個值為‘A’字串字面量。使用hashCode()方法,我們嘗試檢索當前序列的雜湊碼。

package com.tutorialspoint;

public class HashCode {
   public static void main(String[] args) {
      
      //create string literal
      String str = "A";
      System.out.println("The given string is: " + str);
      
      // using hashCode() method
      int str_hash_code = str.hashCode();
      System.out.println("The hash code of the current string is: " + str_hash_code);
   }
}

輸出

上述程式產生以下輸出:

The given string is: A
The hash code of the current string is: 65
java_lang_string.htm
廣告