Java 系統 identityHashCode() 方法



描述

Java System identityHashCode() 方法返回給定物件的雜湊碼,該雜湊碼與預設方法 hashCode() 返回的雜湊碼相同。空引用的雜湊碼為零。

宣告

以下是 java.lang.System.identityHashCode() 方法的宣告

public static int identityHashCode(Object x)

引數

x − 這是要計算雜湊碼的物件。

返回值

此方法返回雜湊碼。

異常

示例:獲取檔案的雜湊碼

以下示例顯示了 Java System identityHashCode() 方法的使用。我們建立了三個 File 物件,並使用 identityHashCode() 方法獲取並列印它們的雜湊碼。

package com.tutorialspoint;

import java.io.File;

public class SystemDemo {

   public static void main(String[] args) throws Exception {

      File file1 = new File("amit");
      File file2 = new File("amit");
      File file3 = new File("ansh");

      // returns the HashCode
      int ret1 = System.identityHashCode(file1);
      System.out.println(ret1);

      // returns different HashCode for same filename
      int ret2 = System.identityHashCode(file2);
      System.out.println(ret2);

      // returns the HashCode    
      int ret3 = System.identityHashCode(file3);
      System.out.println(ret3);
   }
} 

輸出

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

1159190947
925858445
798154996

示例:獲取字串的雜湊碼

以下示例顯示了 Java System identityHashCode() 方法的使用。我們建立了三個字串,並使用 identityHashCode() 方法獲取並列印它們的雜湊碼。

package com.tutorialspoint;

public class SystemDemo {

   public static void main(String[] args) throws Exception {

      String name1 = new String("amit");
      String name2 = new String("amit");
      String name3 = new String("ansh");

      // returns the HashCode
      int ret1 = System.identityHashCode(name1);
      System.out.println(ret1);

      // returns different HashCode for same name2
      int ret2 = System.identityHashCode(name2);
      System.out.println(ret2);

      // returns the HashCode    
      int ret3 = System.identityHashCode(name3);
      System.out.println(ret3);
   }
} 

輸出

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

1159190947
925858445
798154996

示例:獲取物件的雜湊碼

以下示例顯示了 Java System identityHashCode() 方法的使用。我們建立了三個 Student 物件,並使用 identityHashCode() 方法獲取並列印它們的雜湊碼。

package com.tutorialspoint;

public class SystemDemo {

   public static void main(String[] args) throws Exception {

      Student student1 = new Student(1, "Julie") ;
      Student student2 = new Student(1, "Julie") ;
      Student student3 = new Student(2, "Adam") ;

      // returns the HashCode
      int ret1 = System.identityHashCode(student1);
      System.out.println(ret1);

      // returns different HashCode for same student
      int ret2 = System.identityHashCode(student2);
      System.out.println(ret2);

      // returns the HashCode    
      int ret3 = System.identityHashCode(student3);
      System.out.println(ret3);
   }
} 
class Student {
   int rollNo;
   String name;

   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
   }

   @Override
   public String toString() {
      return "[ " + this.rollNo + ", " + this.name + " ]";
   }
}

輸出

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

925858445
798154996
681842940
java_lang_system.htm
廣告