For simple data types, Set will work to avoid the duplicates using the Object class equals() and hashcode() methods, but to utilize the same behavior for the complex data types, we have to override the hashcode() and equals() methods as shown in the below example:
package core.collections;
import java.util.HashSet;
import java.util.Set;
/*If a set of different Employee type objects having variables first name and last name as a members and two of the employee type objects having same first name and last name how can you avoid the duplicate employee objects ? and if you print the size of the set what will be the output ?*/
public class EmployeeCompare {
public static void main(String[] args) {
Set<Employee> employees = new HashSet<Employee>();
employees.add(new Employee("Kalyan Valluru"));
employees.add(new Employee("Rani Marthala"));
employees.add(new Employee("Kalyan Valluru"));
System.out.println("Employees Count is: "+employees.size());
System.out.println(employees);
}
}
class Employee{
private String fullName;
public Employee(String fullName){
this.fullName = fullName;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
@Override
public String toString() {
return this.fullName;
}
@Override
public int hashCode() {
return this.fullName.hashCode();
}
@Override
public boolean equals(Object obj) {
Employee other = (Employee) obj;
if (!fullName.equals(other.fullName))
return false;
else
this.fullName = fullName;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
@Override
public String toString() {
return this.fullName;
}
@Override
public int hashCode() {
return this.fullName.hashCode();
}
@Override
public boolean equals(Object obj) {
Employee other = (Employee) obj;
if (!fullName.equals(other.fullName))
return false;
else
return true;
}
}
}
The size of the set above is 2
ReplyDelete