-1

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!

Biyu
  • 513
  • 1
  • 5
  • 30
  • 2
    Did you override `hashCode` and `equals` in `Employee` class? – Eran Jan 07 '18 at 07:11
  • No, That what i want to understand actually. Please explain a bit – Biyu Jan 07 '18 at 07:12
  • Please read the Javadoc of HashSet as well as `equals` and `hashCode` methods of `Object` class. – Eran Jan 07 '18 at 07:13
  • thanks Eran, I got a clue by your sentence "override hashCode and equals", Saw the Object class, String class has overriden it while Employee not. Hence I am getting variation. Thanks a lot – Biyu Jan 07 '18 at 07:16

2 Answers2

1

The equals and hashCode inherited from Object have identity semantics, i.e. only the exact same instance is equal to itself.

It is different for String because it implements its own version of equality.

You need to do the same for your class if you want another definition of equality.

Henry
  • 42,982
  • 7
  • 68
  • 84
0

As we all know, Hashset doesn't allow duplicates. It does this duplicate check using hashcode() and equals() methods.

If you did not provide the implementation for these methods in your class (in your case, Employee class), the default implementation in Object class will be invoked which uses the object's hexadecimal address to state whether two objects are equal, rather than the content of the object. Overriding these two methods carefully results in expected outcome.

Nagendra Varma
  • 2,215
  • 3
  • 17
  • 26