1. java.lang.Object类中有两个非常重要的方法:
public native int hashCode();
public boolean equals(Object obj) {
return (this == obj);
}
Object类是类继承结构的基础,所以是每一个类的父类。所有的对象,包括数组,都实现了在Object类中定义的方法。
在object类中,hashcode()方法是本地方法,返回的是对象的地址值,而object类中的equals()方法比较的也是两个对象的地址值。如果equals()相等,说明两个对象地址值也相等,当然hashcode()也就相等了。
补充一点关于equals()和==的区别:(原文链接:https://blog.youkuaiyun.com/qq_36522306/article/details/80550210)
= =在用于基本数据类型的比较时,比较的是两个数据是否相等,在用于引用类型的比较时,比较的是堆中数据在栈中的引用是否相同,用来判断两个对象的地址是否相同,即是否是指相同一个对象。
equals一般用来比较的是两个对象的内容是否相等,由于所有的类都是继承自java.lang.Object类的,所以适用于所有对象,如果没有对该方法进行覆盖的话,调用的仍然是Object类中的方法,而Object中的equals方法返回的却是==的判断,即判断的还是内存地址。
一下是一小段关于hashcode()源码解释:
* If two objects are equal according to the {@code equals(Object)}
* method, then calling the {@code hashCode} method on each of
* the two objects must produce the same integer result.
* It is <em>not</em> required that if two objects are unequal
* according to the {@link java.lang.Object#equals(java.lang.Object)}
* method, then calling the {@code hashCode} method on each of the
* two objects must produce distinct integer results. However, the
* programmer should be aware that producing distinct integer results
* for unequal objects may improve the performance of hash tables.
即:
equals()相同,hashCode()肯定相同;
equals()不同,hashCode()不一定不相同;(此情况就是哈希冲突);