首先判断这两个对象是不是同一个对象,直接使用“==”,进行比较,如果是直接返回true;
再判断传入的这个对象是不是为null,也是使用“==”,如果为null,返回一个FALSE;
最后比较他们的各个属性是否相等;
实例代码:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package testdemo;
class Person{
private String name;
private int age;
public Person(String name, int age){
this.name = name;
this.age = age;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
public void setName(String name){
this.name = name;
}
public void setAge(int age){
this.age = age;
}
public boolean compare(Person per){
if(this == per)
return true;
if(per == null)
return false;
return per.name.equals(this.name) && per.age == this.age;
}
}
/**
*
* @author Jone
*/
public class TestDemo {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Person perA = new Person("wang", 21);
Person perB = new Person("liu", 22);
if(perA.compare(perB))
System.out.println("同一个人");
else
System.out.println("不是同一个人");
}
}