I have 3 classes
Employee class is like
class Employee {
int id;
String name;
long salary;
List<Address> address;
//getter setter, equals and hashcode and parameterized constructor}
And My address class is like
public class Address {
int housenum;
String streetname;
int pincode;
//getter setter and parameterized constructor
}
and My Test class is like
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());
I am getting different hashcode for address objects as I have not overridden equals and hashcode. But why I am getting same hashcode for two different lists of addresses i.e. addressLst1 and addressLst2 And why I am getting the size of set as 1, why the hashcode of two employee object is the same? And what is correct way to override equals and hashcode for the custom object which consist of list of another custom object?