引言:通常面试官问 == 和 equals 区别是什么? 有些人会回答 == 判断对象是否是同一个对象判断引用是否相同 equals 判断值是否相同
==:用于判断两个对象的地址是不是相同。判断是不是同一个对象(基本数据类型比较的是值,引用类型比较的是内存地址)
equals:
情况1:可以看到底层代码 如果类对equals(Object obj) 未进行覆盖时 与 == 是一样的
情况2:当类覆盖了equals()方法。一般覆盖两个对象的额内容相等,如果相等,则返回 true (认为两个对象相等)(String类 的equals方法是被重写过)
equals源码:
public class Object {
...
public boolean equals(Object obj) {
return (this == obj);
}
...
}
实例:HashMap中覆盖的equals()方法
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Map))
return false;
Map<?,?> m = (Map<?,?>) o;
if (m.size() != size())
return false;
try {
Iterator<Entry<K,V>> i = entrySet().iterator();
while (i.hasNext()) {
Entry<K,V> e = i.next();
K key = e.getKey();
V value = e.getValue();
if (value == null) {
if (!(m.get(key)==null && m.containsKey(key)))
return false;
} else {
if (!value.equals(m.get(key)))
return false;
}
}
} catch (ClassCastException unused) {
return false;
} catch (NullPointerException unused) {
return false;
}
return true;
}
HashCode():是获取哈希码,也称为散列码;返回一个int整数都确定在哈希表中的位置(只在哈希表为基础的集合有用)且是定义在Object.java中的,任何类都会有该函数
源码注释规定HashCode:
public class Object {
...
public native int hashCode();
* <p>
* Note that it is generally necessary to override the {@code hashCode}
* method whenever this method is overridden, so as to maintain the
* general contract for the {@code hashCode} method, which states
* that equal objects must have equal hash codes.
/**请注意,通常有必要覆盖{@code hashCode}
方法,只要此方法被覆盖,即可保持
{@code hashCode}方法的一般合同,其中规定
相等的对象必须具有相等的哈希码。
**/
* @param obj the reference object with which to compare.
* @return {@code true} if this object is the same as the obj
* argument; {@code false} otherwise.
* @see #hashCode()
* @see java.util.HashMap
*/
...
}
HashCode()与equals()规定:
1.相等的对象必须具有相等的哈希码(但两个对象有相同的HashCode 不一定是同一个对象)
2.如果两个对象相等,两个对象调用equals都会返回true (如上)
因此:如果equals方法被覆盖过,则HashCode方法也必须被覆盖