概述
Java中equals用于比较字符串内容。
/**
* 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.
*
* <p>For finer-grained String comparison, refer to
* {@link java.text.Collator}.
*
* @param anObject
* The object to compare this {@code String} against
*
* @return {@code true} if the given object represents a {@code String}
* equivalent to this string, {@code false} otherwise
*
* @see #compareTo(String)
* @see #equalsIgnoreCase(String)
*/
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String aString = (String)anObject;
if (!COMPACT_STRINGS || this.coder == aString.coder) {
return StringLatin1.equals(value, aString.value);
}
}
return false;
}
...
@IntrinsicCandidate
public static boolean equals(byte[] value, byte[] other) {
if (value.length == other.length) {
for (int i = 0; i < value.length; i++) {
if (value[i] != other[i]) {
return false;
}
}
return true;
}
return false;
}
字符串存储的时候是以字符数组形式进行存储,比较时比较的是字符的编码。若有一个字符编码不同,则两个字符串内容不相等。若是对String属性不太了解,可以看一下 Java随笔-String 。
使用
public class EqualTest {
public static void main(String[] args) {
System.out.println("string".equals(null));
}
}
结果:
false
但是也有很多将可能为null的变量放在前面进行比较。
public static void main(String[] args) {
String str = null;
System.out.println(str.equals("String"));
}
结果:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "str" is null
at equal.EqualTest.main(EqualTest.java:12)
出现了空指针异常。