JAVA——【经验】(Java)判断两个对象的属性是否相等
class Doctor{//Doctor类
private String name;
private int age;
private char gender;//性别
private String job;
private double sal;//薪水
public Doctor(String name, int age, char gender, String job, double sal) {
super();
this.name = name;
this.age = age;
this.gender = gender;
this.job = job;
this.sal = sal;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}
public boolean equals(Object obj) {
if(this == obj){//判断比较两个对象是否为同一个对象,若为同一对象属性肯定会完全相同
return true;
}
if(!(obj instanceof Doctor)) {//判断obj是否为Doctor的实例对象或者子类
return false; //不是返回false
}
//若能运行到此处,即说明obj运行类型为Doctor或者是其子类
//因此能向下转型,把obj转为Doctor
Doctor doctor = (Doctor)obj;
return this.name.equals(doctor.name) && this.age == doctor.age
&& this.gender == doctor.gender && this.job == doctor.job
&&this.sal == doctor.sal;
}//一一判断不是同一个对象,但是同一个类型的对象或者为父子关系的对象的属性是否全相等
}
public class Judge {
public static void main(String[] args) {
Doctor d1 = new Doctor("张飞", 20, '男', "送快递", 3000);
Doctor d2 = new Doctor("张飞", 20, '男', "送快递", 3000);
Doctor d3 = new Doctor("张飞", 20, '男', "送快递", 6000);
System.out.println("对象d1和d2属性是否相等?比较结果:"+d1.equals(d2));
System.out.println("对象d1和d1属性是否相等?比较结果:"+d1.equals(d1));
System.out.println("对象d1和d3属性是否相等?比较结果:"+d1.equals(d3));
}
}