Java 物件 hashCode() 方法



描述

Java Object hashCode() 方法返回物件的雜湊碼值。此方法是為了支援雜湊表(例如 java.util.Hashtable 提供的雜湊表)而提供的。

宣告

以下是 java.lang.Object.hashCode() 方法的宣告

public int hashCode()

引數

返回值

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

異常

獲取 GregorianCalendar 的雜湊碼示例

以下示例演示了 java.lang.Object.hashCode() 方法的使用。在此程式中,我們建立了一個新的 GregorianCalendar 類例項。現在使用 hashCode() 方法列印日曆例項的雜湊碼。

package com.tutorialspoint;

import java.util.GregorianCalendar;

public class ObjectDemo {

   public static void main(String[] args) {

      // create a new GregorianCalendar object
      GregorianCalendar cal = new GregorianCalendar();

      // print current time
      System.out.println("" + cal.getTime());

      // print a hashcode for cal
      System.out.println("" + cal.hashCode());
   }
}

輸出

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

Fri May 31 16:14:27 IST 2024
943043264

獲取 Integer 的雜湊碼示例

以下示例演示了 java.lang.Object.hashCode() 方法的使用。在此程式中,我們建立了一個新的 Integer 類例項。現在使用 hashCode() 方法列印整數例項的雜湊碼。

package com.tutorialspoint;

public class ObjectDemo {

   public static void main(String[] args) {
      // create a new Integer
      Integer i = Integer.valueOf(5);

      // print i
      System.out.println("" + i);

      // print hashcode for i
      System.out.println("" + i.hashCode());
   }
}

輸出

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

5
5

獲取 ArrayList 的雜湊碼示例

以下示例演示了 java.lang.Object.hashCode() 方法的使用。在此程式中,我們建立了一個新的 ArrayList 類例項。現在使用 hashCode() 方法列印 arrayList 例項的雜湊碼。

package com.tutorialspoint;

import java.util.ArrayList;

public class ObjectDemo {

   public static void main(String[] args) {
      // create a new ArrayList
      ArrayList<String> i = new ArrayList<>();

      // print i
      System.out.println("" + i);

      // print hashcode for i
      System.out.println("" + i.hashCode());
   }
}

輸出

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

[]
1
java_lang_object.htm
廣告