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
广告

© . All rights reserved.