我想知道如何检查同一类的两个对象在每个属性中是否具有相同的值。
例如:
public class Person {
String name;
String surname;
String country;
int age;
public Person(String name, String surname, String country, int age) {
this.name = name;
this.surname = surname;
this.country = country;
this.age = age;
}
public boolean samePerson(Person person){
//CODE
}
Person person1 = new Person("Abel", "Smith", "EEUU", 26);
Person person2 = new Person("Alexa", "Williams", "Canada", 30);
Person person3 = new Person("Abel", "Smith", "EEUU", 26);
Person person4 = new Person("Alexa", "Williams", "EEUU", 30)
person1.samePerson(person2) // return false
person1.samePerson(person3) // return true
person2.samePerson(person3) // return false
person2.samePerson(person4) // return false
我唯一能想到的就是将属性一一比较。有没有更简单的方法?
对不起我的英语
提前致谢
最佳答案
The only thing I can think of is to compare the attributes one to one. Is there a simpler way?
不幸的是没有。您必须编写代码才能做到这一点。如果这样做,请考虑将该代码放入 equals
和 hashCode
方法中。
关于Java:检查同一类的两个对象是否具有相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23385182/