public class Employee{
int empId;
String empName;
List <EmployeeAddress> empAdd;
// getters & setters
}
public class EmployeeAddress{
String city;
String state;
// getters & setters
}
现在我制作了两个员工类对象,并想对它们进行比较。我在员工类中使用了列表,因为员工可以有多个地址。需要这方面的帮助
最佳答案
因为不清楚“比较”的含义,我想您需要重写 Employee
类中的 equals
方法。
首先,我建议您看看这个有趣的问题:What issues should be considered when overriding equals and hashCode in Java?
然后根据equals
List
接口(interface)的方法契约:
two lists are defined to be equal if they contain the same elements in the same order. This definition ensures that the equals method works properly across different implementations of the List interface.
所以你可以编写如下代码:
@Override
public boolean equals(Object obj) {
Employee e = (Employee) obj;
return this.empId == e.empId && this.empName.equals(e.empName) && this.empAdd.equals(e.empAdd);
}
或者您可以定义列表比较的自定义逻辑...
关于java - 如何比较 Java 中属性中也包含列表的两个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28587317/