Java - Short hashCode() 方法



Java Short hashCode() 方法檢索給定 Short 物件的雜湊碼。Java 中的每個物件都有一個關聯的雜湊碼,它是一個唯一的原始整數值。此方法檢索的值與 intValue() 方法返回的值相同。

使用計算機科學中基本的雜湊概念,物件或實體被對映到整數值。這些值被稱為實體的雜湊值或雜湊碼。

此方法有兩個多型變體。下面將討論這些變體的語法。

語法

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

public int hashCode() 
or,
public static int hashCode(short x)

引數

  • x − 它是雜湊值

返回值

給定 Short 物件的雜湊碼

獲取具有正值的 Short 物件的雜湊碼示例

以下示例顯示了 Java Short hashCode() 方法的用法。這裡我們建立一個具有正值的 Short 物件。然後使用此方法列印雜湊碼:

package com.tutorialspoint;

public class ShortDemo {
   public static void main(String[] args) {
      short value1 = 8487;
      Short value2 = new Short(value1);
      
      // The hash code method
      int value3 = value2.hashCode();
      System.out.println("The Hash code value is = " + value3);
      
      // The hash code static method
      Short value4 = new Short("8487");
      System.out.println("The short value is  = " + Short.hashCode(value4));
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

The Hash code value is = 8487
The short value is  = 8487

獲取具有正值的 Short 物件的雜湊碼示例

以下是 hashCode() 方法的另一個示例:

package com.tutorialspoint;

public class ShortDemo {
   public static void main(String[] args) {
      
      // create the Short objects
      Short value1 = 87;
      Short value2 = 987;
      
      // print the hashcode of the Short objects
      System.out.println("hashCode of value1 is: " + value1.hashCode());
      System.out.println("hashCode of value2 is: " + value2.hashCode());
   }
}

輸出

以下是上述程式碼的輸出:

hashCode of value1 is: 87
hashCode of value2 is: 987

獲取具有負值的 Short 物件的雜湊碼示例

在下面的示例中,我們嘗試查詢負值的雜湊碼:

package com.tutorialspoint;

public class ShortDemo {
   public static void main(String[] args) {
      
      // passing the negative integer
      Short value1 = new Short("-36");
      System.out.println("Hash Value of negative integer is = " + value1.hashCode());
   }
}

輸出

執行上述程式後,獲得的輸出如下:

Hash Value of negative integer is = -36

獲取 Short 物件的雜湊碼示例

在下面的程式碼中,將負值和正值 short 值作為引數傳遞,以列印傳遞值的等效雜湊碼值:

package com.tutorialspoint;

public class ShortDemo {
   public static void main(String[] args) {
      short s1 = 987;
      short s2 = -786;
      
      // returning the hash code value
      int h1 = Short.hashCode(s1);
      int h2 = Short.hashCode(s2);
      System.out.println("hash code value of s1 is: " + h1);
      System.out.println("hash code value of s2 is: " + h2);
   }
}

輸出

執行上述程式碼時,我們得到以下輸出:

hash code value of s1 is: 987
hash code value of s2 is: -786
java_lang_short.htm
廣告