Java中使用“==”来判断两个对象是否相等是判断两个对象的引用是否相同
Java中使用“equals”来判断两个对象是否相等默认是判断两个对象的引用是否相同,然而还需看对象的equals方法是否被重写。一般来说,Java中String的equals被重写了,判断的是两个String对象字符串级别是否相同。
package Chapter03;
class Cat3{
int height, weight;
Cat3(int height, int weight){
this.height = height;
this.weight = weight;
}
public boolean equals(Object obj){
if (obj instanceof Cat3){
Cat3 c = (Cat3) obj;
if (c.height == this.height && c.weight == this.weight){
return true;
}
}
return false;
}
}
public class equalsDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Cat3 c1 = new Cat3(5, 10);
Cat3 c2 = new Cat3(5, 10);
System.out.println(c1==c2);
System.out.println(c1.equals(c2));
String s1 = new String("hello"); # false
String s2 = new String("hello"); # true
System.out.println(s1==s2); # false
System.out.println(s1.equals(s2)); # true
}
}
网友评论