为什么对象列表中的Equals和Hashcode相同,即使我尚未为该对象实现那些方法也是如此

问题描述 投票:2回答:1

我有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,为什么两个雇员对象的哈希码相同?覆盖包含另一个自定义对象列表的自定义对象的等于和哈希码的正确方法是什么?

java collections hashmap equals hashcode
1个回答
2
投票

两个ListaddressLst1以完全相同的顺序包含完全相同的元素,因此addressLst2List的合约要求这两个equals等于彼此:

boolean java.util.List.equals(Object o)

比较指定对象与此列表是否相等。当且仅当指定对象也是一个列表,并且两个列表具有相同的大小,并且两个列表中所有对应的元素对相等时,才返回true。 (如果(e1 == null?e2 == null:e1.equals(e2)),则两个元素e1和e2相等。)换句话说,如果两个列表包含相同顺序的相同元素,则两个列表定义为相等。 。此定义确保equals方法可在List接口的不同实现中正常工作。

List不会覆盖Addressequals,这没关系,因为hashCode包含对相同对象的引用。 List不等于address1时,两个address2都包含对Listaddress1的引用,并且顺序相同,因此address2相等。

对于List类,您写道您确实覆盖了Employeeequals,所以我假设两个hashCode的所有属性均相等时,它们相等。因此,您尝试添加到Employees的两个Employee实例是相等的。

© www.soinside.com 2019 - 2024. All rights reserved.