话不多说,先给出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;
}
分析
1.代码中可以看出,方法中第一步就判断是的==,如果满足就直接返回true,否则继续往下走
if (this == anObject) {
return true;
}
2.再看第二个if语句,先判断传过来的对象类型是否为String,然后再比较长度,最后比较的是value
从这我们就可以想到,equals方法比较的是String变量的内容是否相同
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;
}
}
所以,equals方法比较的是字符串内容,==判断的是是否是同一个对象,满足==必然满足equals,所以equals先判断==
给出我的练习代码
/**
* equals方法测试
*/
public static void equalsTest(){
System.out.println("*****equals方法和==测试*****");
//两个字符串的内容相同,不用new关键字新建对象
String firstString = "yangqi";
String firstContentCopy = "yangqi";
//两个字符串的内容相同,分别用new关键字新建对象
String secondString = new String("zhoufei");
String secondContentCopy = new String("zhoufei");
//equals方法结果
System.out.println("firstString("+firstString+") equals firstContentCopy("+firstContentCopy+")?");
System.out.println(firstString.equals(firstContentCopy));//结果为true
System.out.println("secondString("+secondString+") equals secondContentCopy("+secondContentCopy+")?");
System.out.println(secondString.equals(secondContentCopy));//结果为true
//==比较结果
System.out.println("firstString("+firstString.hashCode()+")==firstContentCopy("+firstContentCopy.hashCode()+")?");
System.out.println(firstString==firstContentCopy);//结果为true
System.out.println("secondString("+secondString.hashCode()+")==secondContentCopy("+secondContentCopy.hashCode()+")?");
System.out.println(secondString==secondContentCopy);//结果为false
}
运行结果
其中,用new关键字和不用new关键字的区别,在以后的博文中探讨.