First, I would suggest that it would be good to change your List<EmployeeAddress>
to Set<EmployeeAddress>
. This helps in two ways:
- It will avoid duplicate addresses in the list of addresses for each employee.
- It will make two employees equal without regard of the order in which addresses appear, since their is no order in a set.
Having said that, be sure that the equals method of EmployeeAddress is well implemented too, since the Set interface will require it to function properly when detecting duplicates. And then you would implement equals as:
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Employee)) {
return false;
}
Employee other = (Employee) obj;
if (this.empAdd == null) {
if (other.empAdd != null) {
return false;
}
} else if (!this.empAdd.equals(other.empAdd)) {
return false;
}
if (this.empId != other.empId) {
return false;
}
if (this.empName == null) {
if (other.empName != null) {
return false;
}
} else if (!this.empName.equals(other.empName)) {
return false;
}
return true;
}
The implementation of the equals method for the EmployeeAddress class should be as follows:
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof EmployeeAddress)) {
return false;
}
EmployeeAddress other = (EmployeeAddress) obj;
if (this.city == null) {
if (other.city != null) {
return false;
}
} else if (!this.city.equals(other.city)) {
return false;
}
if (this.state == null) {
if (other.state != null) {
return false;
}
} else if (!this.state.equals(other.state)) {
return false;
}
return true;
}