equals()方法比较其他某个对象是否与此对象“相等”,意思就是两个对象是否指向同一内存地址。
String,Date等类中已经重写了equals()方法,所以可以直接使用。
API文档中对String中equals()方法的描述如下:
public boolean equals(Object anObject)
-
将此字符串与指定的对象比较。当且仅当该参数不为
null
,并且是与此对象表示相同字符序列的String
对象时,结果才为true
。
String s1 = new String("Hello!");
String s2 = new String("Hello!");
...
s1.equals(s2);
返回true
如果不重写equals()方法,那么s1.equals(s2)默认比较两个对象所指向的内存地址是否相同,返回值必然为false.
以下程序比较两只猫是否相同:
class Cat{
String color;
int height,weight;
//定义猫的属性
Cat(String color,int height,int weight){
this.color = color;
this.height = height;
this.weight = weight;
}
//重写equals()方法,判断两个对象的属性是否完全相同
public boolean equals(Object obj){
if(obj == null) return false;
else {
if(obj instanceof Cat){
Cat c = (Cat) obj;
if(c.color == this.color && c.height == this.height && c.weight == this.weight)
return true;
}
}
return false;
}
}
class testEquals{
public static void main(String[] args){
Cat c1 = new Cat("yellow",2,3);
Cat c2 = new Cat("yellow",2,3);
System.out.println(c1.equals(c2));
}
}
输出:
true