比较两个对象属性是否相等没必要重新定义一个类,把两个对象当做参数传进去
可以使用this解决该问题(因为这是两个对象,其中一个对象可以用来调用方法)
p1.compareTo(p2)
//此时该方法中使用的this即代表p1
代码如下:
//2024.07.13
public class TestPerson {
public static void main(String[] args) {
Person p1 = new Person("jack", 18);
Person p2 = new Person("jack", 18);
System.out.println(p1.compareTo(p2));
}
}
class Person {
String name;
int age;
public Person(String name, int age){
this.name = name;
this.age = age;
}
public boolean compareTo(Person p){
return this.name.equals(p.name) && this.age == p.age;//p1 is the current object
}
}
运行截图如下: