hashCode()
方法的语法是:
object.hashCode()
hashCode() 参数
hashCode()
方法不接受任何参数。
hashCode()返回值
- 返回对象的哈希码值
注意:哈希码值是与每个对象关联的整数值。它用于在哈希表中标识对象的存储位置。
示例 1:Java 对象 hashCode()
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()
方法来获取String和ArrayList对象的哈希码。
这是因为String
和ArrayList
类继承了Object
类。
示例 3:相等对象的哈希码值
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
}
}
在上面的示例中,我们可以看到两个对象 obj1 和 obj2 生成了相同的哈希码值。
这是因为这两个对象是相等的。根据官方Java文档,两个相等的对象应始终返回相同的哈希码值。
注意:我们使用了Java Object equals() 方法来检查两个对象是否相等。