String的equals()方法的重写是写在java.lang.String里面的,不是在这里,这里只是个示意例子,让你比较 == 和 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 = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
============================================
如ls所说,Object类的equals方法比较的是hashCode,如果String在没有重写equals的情况下
s1.equals(s2)返回应该是false,但是事实是它返回的是true,这就是书中所说的String的equals方法已经被重写
====================为了更深刻的说明,我们来重写下你的这个例子中MyValue的equals的方法,然后你和你现在的例子比较一下就知道了
public class OperatorsAndExpressions { //操作和表达
/**
* @param args
*/
void equalsMethod2(){
String s1=new String("hello");
String s2=new String("hello");
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
class MyValue{ //内部类,是用户自己定义的类因此,类MyValue的equals()方法是从
int i;//Object类继承的,其功能仍然是比较两个操作数是否是同一个对象
//为了更深刻说明重写equals方法的作用,我们来这里重写一下equals
@Override
public boolean equals(Object o){
if(this == o){
return true;
}
if(o instanceof MyValue){
if(((MyValue)o).i == this.i){
return true;
}
}
return false;
}
}
MyValue v1=new MyValue();
MyValue v2=new MyValue();
v1.i=v2.i=2003;
System.out.println(v1.equals(v2));
}
public static void main(String[] args) {
// TODO Auto-generated method stub
OperatorsAndExpressions OperAndExp=new OperatorsAndExpressions();
//一元算术运算符的运用
OperAndExp.equalsMethod2();
}
}
=============================
原例子的运行结果
false
true
false
--------------改写后的运行结果
false
true
true
温馨提示:答案为网友推荐,仅供参考