在Object这个类里面equals方法默认的实现是当前对象引用和你要比较的对象的引用是不是同一个对象。 equals方法的返回值是boolean j2sdk提供了一些类,如:String Data等重写了equals方法例子程序:
Java代码public class TestEquals {
public static void main(String[] args) {
Cat c1 = new Cat(1, 2, 3);
Cat c2 = new Cat(1, 2, 6);
System.out.println(c1 == c2); //false
System.out.println(c1.equals(c2)); //false
String s1 = new String("hello");
String s2 = new String("hello");
String m1 = "hello";
String m2 = "hello";
System.out.println(s1 == s2); //false
System.out.println(m1 == m2); //true
System.out.println(s1.equals(s2)); //true
}
}
//实体类
class Cat {
int color;
int height, weight;
public Cat(int 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;
}
}
更多Object类之equals方法 相关文章请关注PHP中文网!
本文原创发布php中文网,转载请注明出处,感谢您的尊重!