Java教程

Java Object hashCode()

Java Object hashCode()

Java Object hashCode() 方法返回与对象关联的哈希码值。
hashCode() 方法的语法是:
object.hashCode()

hashCode() 参数

hashCode() 方法不带任何参数。

hashCode() 返回值

返回对象的哈希码值
注意: 哈希码值是与每个对象关联的整数值。它用于标识对象在哈希表中的位置。

示例 1: Java ObjecthashCode()

class Main {
  public static void main(String[] args) {
    // hashCode() with Object
    Object obj1 = new Object();
    System.out.println(obj1.hashCode());  // 1785210046
    Object obj2 = new Object();
    System.out.println(obj2.hashCode());  // 1552787810
    Object obj3 = new Object();
    System.out.println(obj3.hashCode());  // 1361960727
  }
}
注意: Object 类是 Java 中所有类的超类。因此,每个类都可以实现 hashCode() 方法。

示例 2: 带有 String 和 ArrayList 的 hashCode()

import java.util.ArrayList;
class Main {
  public static void main(String[] args) {
    // hashCode() with String
    String str = new String();
    System.out.println(str.hashCode());  // 0
    ArrayList<Integer> list = new ArrayList<>();
    System.out.println(list.hashCode());  // 1
  }
}
在上面的例子中,我们可以调用 hashCode()方法来获取 StringArrayList对象的哈希码。
这是因为 StringArrayList类继承了 Object类。

示例 3: Equals 对象的哈希码值

class Main {
  public static void main(String[] args) {
    // hashCode() with Object
    Object obj1 = new Object();
    // assign obj1 to obj2
    Object obj2 = obj1;
    // check if two objects are equal
    System.out.println(obj1.equals(obj2));  // true
    // get hashcode of obj1 and obj2
    System.out.println(obj1.hashCode());   // 1785210046
    System.out.println(obj2.hashCode());   // 1785210046
  }
}
在上面的例子中,我们可以看到两个对象 obj1obj2 正在生成相同的哈希码值。
这是因为两个对象是相等的。而且,根据官方 Java 文档,两个相等的对象应始终返回相同的哈希码值。
注意: 我们已经使用 Java Object equals() 方法来检查两个对象是否相等。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4