Suppose you have an HashSet object and you want that when an Employee object is added it should check all its attributes and they are different then only it should allow to add the object to it.
For e.g. below 2 objects are similar so it should not allow both to be added:
Employee e1=new Employee(“Prasanna”,44);
Employee e2=new Employee(“Prasanna”,44);
So here is the program:
class Employee{ private int age; private String name; public Employee(String name, int age) { this.age=age; this.name=name; } @Override public int hashCode() { return this.name.hashCode(); } @Override public boolean equals(Object o) { if(this.name.equals(((Employee)o).name) && this.age == ((Employee)o).age) return true; else return false; } } public class Manager{ public static void main(String[] args) { Set set=new HashSet(); Employee e1=new Employee("Prasanna",44); Employee e2=new Employee("Prasanna",44); set.add(e1); set.add(e2); System.out.println(set.size()); } }
Output:
Total items added in HashSet: 1