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 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()方法检查两个对象是否相等。