1.==号
==号比较的是两个String对象的地址(或引用)相等。
2.equal
String的equals方法,重写Object的equals方法,比较的是两个String对象字符串内容是否相等
附上Object的equals方法和String的equals方法
2.1 Object的equals方法,比较的是两个对象的地址是否相等
public boolean equals(Object obj) {
return (this == obj);
}
2.2 String的equals方法,this.equals(obj),
1.传入的Obj是一个String引用并且内存地址和this相等。(即this和obj二者指向同一个String对象)
2.传入的obj是String引用,但和this指向的String对象不是同一个,但是内容相同(内容相同比较方式:1.将两个String转变为字符数组;2.比较字符数组的每一位是否相同,若每一位都相同返回true,否则返回false)
1和2,返回true。
/**
* 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
*/
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;
}
3.两个例子对比
例子1:
String s1 ="Monday";
String s2 ="Monday";
//说明常量池里“Monday”是同一个
if (s1 == s2) {
System.out.println("s1 == s2");
} else{
System.out.println("s1 != s2");
}
if(s1.equals(s2)){
System.out.println("s1 == s2");}
else{
System.out.println("s1 != s2");
}
结果:s1 == s2
s1 == s2
例子2: