我有三个类
员工阶级就像
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
}
我的测试课就像
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());
我为地址对象获得了不同的哈希代码,因为我没有覆盖equals和哈希代码。但是,为什么我为两个不同的地址列表(即addressLst1和addressLst2(获得相同的哈希代码,为什么我将集合的大小设置为1,为什么两个员工对象的哈希代码相同?对于由另一个自定义对象列表组成的自定义对象,覆盖equals和hashcode的正确方法是什么?
两个List
的addressLst1
和addressLst2
包含完全相同的元素,顺序完全相同,因此List
的equals
的契约要求这两个List
彼此相等:
布尔java.util.List.equals(Object o(
将指定的对象与此列表进行相等性比较。当且仅当指定的对象也是一个列表,两个列表的大小相同,并且两个列表中所有对应的元素对都相等时,返回true。(如果(e1==null?e2==null:e1。equals(e2((,则两个元素e1和e2相等。(换句话说,如果两个列表以相同的顺序包含相同的元素,则它们被定义为相等。此定义确保equals方法在List接口的不同实现中正常工作。
Address
不覆盖equals
和hashCode
并不重要,因为List
包含对相同对象的引用。虽然address1
不等于address2
,但两个List
都以相同的顺序包含对address1
和address2
的引用,因此List
是相等的。
对于Employee
类,您写道您确实覆盖了equals
和hashCode
,所以我假设两个Employees
是相等的,如果它们的所有属性都相等。因此,您尝试添加到Set
的两个Employee
实例是相等的。