System.identityHashCode(Object obj) 和 obj.hashCode() 都用于获取对象的哈希码,但它们有显著的区别:
System.identityHashCode(Object obj):
- 返回对象的默认哈希码,这个哈希码是基于对象的内存地址生成的,而不受对象的 hashCode() 方法的重写影响。
- 适用于需要确保唯一标识对象实例的场景。
obj.hashCode():
- 返回对象的哈希码,这个哈希码可以被重写,以便根据对象的字段值生成自定义哈希码。
- 常用于哈希表(如 HashMap 和 HashSet)中,以确保对象的逻辑相等性。
直接看下面代码例子就懂了:
class Main {
public static void main(String[] args) {
MyObject obj1 = new MyObject(1);
MyObject obj2 = new MyObject(1);
// 使用 System.identityHashCode 方法
System.out.println("System.identityHashCode(obj1): " + System.identityHashCode(obj1));
System.out.println("System.identityHashCode(obj2): " + System.identityHashCode(obj2));
// 使用对象的 hashCode 方法
System.out.println("obj1.hashCode(): " + obj1.hashCode());
System.out.println("obj2.hashCode(): " + obj2.hashCode());
}
}
class MyObject {
private int id;
public MyObject(int id) {
this.id = id;
}
@Override
public int hashCode() {
return id; // 重写 hashCode 方法,基于 id 字段生成哈希码
}
}