在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方法 。
