我有3个课程
员工类就像
class Employee {
int id;
String name;
long salary;
List<Address> address;
//getter setter, equals and hashcode and parameterized constructor}
我的地址分类就像
public class Address {
int housenum;
String streetname;
int pincode;
//getter setter and parameterized constructor
}
和我的Test类就像
Address address1 = new Address(10, "str 1", 400043);
Address address2 = new Address(10, "str 1", 400043);
List<Address> addressLst1= new ArrayList<>();
List<Address> addressLst2= new ArrayList<>();
addressLst1.add(address1);
addressLst1.add(address2);
addressLst2.add(address1);
addressLst2.add(address2);
Employee employee1 = new Employee(1, "EMP1", 1000, addressLst1);
Employee employee2 = new Employee(1, "EMP1", 1000, addressLst2);
Set<Employee> set = new HashSet<>();
set.add(employee1);
set.add(employee2);
System.out.println(":::::::::::::::addressLst1:::::::::" + addressLst1.hashCode());
System.out.println(":::::::::::::::addressLst2:::::::::" + addressLst2.hashCode());
System.out.println(":::::::::::::::address1:::::::::" + address1.hashCode());
System.out.println(":::::::::::::::address2:::::::::" + address2.hashCode());
System.out.println(":::::::::::::::employee1:::::::::" + employee1.hashCode());
System.out.println(":::::::::::::::employee2:::::::::" + employee2.hashCode());
set.forEach(System.out::println);
System.out.println(":::::::::::::::size:::::::::" + set.size());
由于没有覆盖等于和哈希码,我为地址对象获得了不同的哈希码。但是为什么为什么要为两个不同的地址列表(即addressLst1和addressLst2)获得相同的哈希码?为什么我要将set的大小设为1,为什么两个雇员对象的哈希码相同?覆盖包含另一个自定义对象列表的自定义对象的等于和哈希码的正确方法是什么?
两个List
和addressLst1
以完全相同的顺序包含完全相同的元素,因此addressLst2
的List
的合约要求这两个equals
等于彼此:
boolean java.util.List.equals(Object o)
比较指定对象与此列表是否相等。当且仅当指定对象也是一个列表,并且两个列表具有相同的大小,并且两个列表中所有对应的元素对相等时,才返回true。 (如果(e1 == null?e2 == null:e1.equals(e2)),则两个元素e1和e2相等。)换句话说,如果两个列表包含相同顺序的相同元素,则两个列表定义为相等。 。此定义确保equals方法可在List接口的不同实现中正常工作。
List
不会覆盖Address
和equals
,这没关系,因为hashCode
包含对相同对象的引用。 List
不等于address1
时,两个address2
都包含对List
和address1
的引用,并且顺序相同,因此address2
相等。
对于List
类,您写道您确实覆盖了Employee
和equals
,所以我假设两个hashCode
的所有属性均相等时,它们相等。因此,您尝试添加到Employees
的两个Employee
实例是相等的。