Java 中使用 compareTo() 方法比较对象属性是否正确?
对于比较两个对象的属性是否相同,通常会使用 equals 方法来进行比较。'compareTo' 方法通常用于排序或比较对象的大小顺序,而不是用于判断对象的属性是否相同。
在您提供的代码中,将 compareTo 方法用于属性比较是不太合适的。建议使用 equals 方法来比较两个 Person 对象的属性是否相同。equals 方法是用于判断两个对象是否相等的标准方法。
修改代码如下:
public class TestPerson{
public static void main(String[] args){
Person p1 = new Person('jack',18);
Person p2 = new Person('mack',20);
Person p3 = new Person('mack',20);
System.out.println(p1.equals(p2));
System.out.println(p2.equals(p3));
}
}
class Person{
String name;
int age;
public Person(String name, int age){
this.name = name;
this.age = age;
}
public boolean equals(Object obj){
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Person other = (Person) obj;
return this.name.equals(other.name) && this.age == other.age;
}
}
这样,equals 方法会比较两个 Person 对象的姓名和年龄是否相同,输出结果将会得到预期的属性比较结果。
原文地址: https://www.cveoy.top/t/topic/bCHR 著作权归作者所有。请勿转载和采集!