How set avoid duplicates in java

What you will learn here about Set

  • How set avoid duplicates in java

Before we start knowing how set avoid duplicates in java or why set does not allow duplicates in java we should know the coding contract between hashCode() and equals() in java

Coding contract between hashCode() and equals() in java

  1. If two objects are equal, then they must have the same hash code.
  2. If two objects have the same hash code, they may or may not be equal.

Set implementations such as HashSet, TreeSet internally uses the HashMap which internally uses the Hashcode to determine the duplicates. If two objects are equal, then they must have the same hash code.

How set avoid duplicates in java

Here we will see how set avoid duplicates in java or why set does not allow duplicates in java. Here we will see how set avoids duplicates in java with example

  1. First create the Implementation class object which is shown below in step 1
  2. Implementation class constructor internally create HashMap object which is shown below in step 2
  3. When we add element using add method, Implementation class internally uses put() method of HashMap class which is shown below in step 3 and 4
  4. put() internally uses the putVal() method which uses the hashCode of Object to determine whether element is already present or not which is shown in step 5

How set avoid duplicates in java

You may also like...