一、背景
在java中的equals和==比较规则:
" == "在基本数据类型:比较值内容 引用类型时:比较地址
equals 重写:比较值内容 , equals不重写:比较地址
那么Java中的一些常用类型,对equals是否进行重写,如果进行了重写,则实现了怎么的逻辑?
二、equals函数重写
2.1 String
String作为引用类型,==直接比较地址。String类重写equals函数,源码如下:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
String类的底层实现为final类型的char[],可见String的equals函数比较的是字符串的值是否想等。
2.2 Integer等对象包装器
有时需要将基本类型,例如int转换为对象,所有的基本类型都有一个与之对应的类,这些类统称包装器。这些包装器都有很明显的名字,Integer、Long、Float、Double、Short、Byte、Character、Boolean。
这些包装器重写的equals函数大同小异,其中Integer的equals函数如下:
/**
* Compares this object to the specified object. The result is
* {@code true} if and only if the argument is not
* {@code null} and is an {@code Integer} object that
* contains the same {@code int} value as this object.
*
* @param obj the object to compare with.
* @return {@code true} if the objects are the same;
* {@code false} otherwise.
*/
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
如上,Integer的equals函数会将Integer拆箱比较保存的基本类型值。
2.3 AbstractList