标签:
boolean equals(Object x);
这个方法和运算符“==”是有很大不同,equals实现对象的值在逻辑上是否相等的判断,即而“==”只是简单的判断对象的引用是否相同。
equals的等价性要求其具有如下关系:自反性、对称性、传递性、非空性、一致性。
package equalsTesting;
public class Person {
private String name;
private int age;
public Person(String name,int age){
this.name = name;
this.age = age;
}
public boolean equals(Object x){
if(this == x) return true;
if(x == null) return false;
if(this.getClass()!= x.getClass()) return false;
Person that = (Person)x;
if(this.name != that.name) return false;
if(this.age != that.age) return false;
return true;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Person p1 = new Person("jay",30);
Person p2 = new Person("kim",29);
Person p3 = new Person("jay",30);
System.out.println(p1.equals(p2));
System.out.println(p2.equals(p1));
System.out.println(p1.equals(p3));
System.out.println(p3.equals(p1));
System.out.println(p1.equals(null));
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/flushhj/article/details/47070247