官方给出的解释是:
Compares this string to the specified object. The result is {@code true} if and only if the argument is not {@code null} and is a {@code String} object that represents the same sequence of characters as this object.
翻译过来意思是:将此字符串与指定对象进行比较。当且仅当参数不是null并且是一个与此对象具有相同的字符序列的String对象时,结果为true。
查看源码,总的来说,equals方法首先检查对象是否在内存中相同(即两个引用指向内存中同一对象),然后检查实参是否是String类的实例,接着检查二者是否使用相同的编码(如果适用),最后比较实际的字符串值。如果所有这些条件都满足,方法返回true,表示两个String对象是相等的。
下面逐行解读:
public boolean equals(Object anObject) {
//比较内存中地址是否相同,返回true则表示二者指向内存中同一对象,一定相等
if (this == anObject) {
return true;
}
return (anObject instanceof String aString)
//检查形参是否为String实例
&& (!COMPACT_STRINGS || this.coder == aString.coder)
/*
*1.COMPACT_STRINGS是一个布尔常量,它用于启用或禁用紧凑字符串存储。