Please find the below scenario,
- Creating two String object, inserted in Hashset, output I am getting false (duplicate identified OK)
- Similarly, Created two Employee object emp1, emp2, inserted in Hashset, output I am getting true(WHY ?)
Why hashcode, equals method are not generating different hashcode and equals comparison in case of String but in case of Employee
Employee.java
public final class Employee { }
Main.java
public static void main(String[] args) {
HashSet hashSet = new HashSet<>();
//For string
String s1 = new String();
String s2 = new String();
System.out.println(hashSet.add(s1)); // true
System.out.println(hashSet.add(s2)); // false
Employee emp1 = new Employee();
Employee emp2 = new Employee();
System.out.println(hashSet.add(emp2)); // true
System.out.println(hashSet.add(emp1)); // true
}
Someone please explain in depth.
Thanks in advance!