在以前刚开始了解这两个的时候,只是粗浅的知道比较基本类型等数据的时候可以用==
,但在比较两个字符串的时候,就得用equals进行比较,以前不太明白其中的原理,最近偶然一次机会对这个有个更深的理解。
- 为什么要区分
==
和equals
我们所说的两个字符串是否相等,是指字符串字面量是否相等,如果使用==来判断两个字符串是否相等,那么实际比较的是两个字符串的**存储地址(即内存地址)**是否相等,因此就容易产生以下问题
String str3 = "hello";
String str4 =str3+"";
System.out.println(str3 == str4);
两个String的内容相同,但因为地址指向不同,从而导致结果为false,这时候就得用到equals方法了。
- 关于equals方法的一些实现
真正Object类里面的equals方法其实跟==
一样,甚至它就是用==
来实现的,下面是Object类里面的equals方法:
public boolean equals(Object obj) {
return (this == obj);
}
所以如果我们使用未重写的equals类,跟直接用==
效果是一样的。因此String类之所以能够比较两个字符串里面的值,是因为它对里面的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.
*
* @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 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;
}
因此,并不是只要是equals方法就可以起到对比对象值的作用,想要它起到这个作用,就必须重写equals方法,在自己创建的类里面也是如此。