java - 如何比较 Java 中属性中也包含列表的两个对象

标签 java oop comparison

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/

相关文章:

c# - 为什么我的动态 IEqualityComparer 不起作用?

java - Tapestry 4,从非组件元素获取提交的值

java - 将二维字符串数组分配给一维对象数组

javascript - babel 编译 es6 类,函数未定义

javascript - 如何在不使用全局作用域的情况下将 javascript 分离到文件中?

Python:最大/最小内置函数取决于参数顺序

string - 在实现 insert() 算法时确定字符串值

java - 为什么 JScrollPane 不工作?

java - Youtube API V3 - 如何使用 channel 图标字段搜索视频?

java - 关于继承的Java类的性质的问题