DEV Community

Code Green
Code Green

Posted on • Edited on

Why Set Doesn't Allow Duplicates in Java

In Java, a Set is a collection that does not allow duplicate elements. This behavior is enforced by the underlying implementations of the Set interface, such as HashSet, TreeSet, and LinkedHashSet.

The main reason Sets do not allow duplicates is due to the contract defined by the Set interface:

  • Uniqueness: Sets are designed to store unique elements only. Each element must be unique based on its equals() method. If an attempt is made to add an element that already exists in the Set, the add operation will return false (for HashSet and TreeSet) or simply not add the element (for LinkedHashSet).
  • Efficiency: By disallowing duplicates, Sets can optimize operations like searching and adding elements. HashSet, for example, uses a hash table for storage, making lookups and insertions constant time on average.
  • Behavior consistency: Sets are often used in scenarios where uniqueness of elements is crucial, such as storing keys in maps or managing collections of distinct entities.

Here's a simple example demonstrating the behavior of a HashSet, which is a common implementation of the Set interface:


    import java.util.HashSet;
    import java.util.Set;

    public class SetExample {
        public static void main(String[] args) {
            Set<Integer> set = new HashSet<>();
            set.add(1);
            set.add(2);
            set.add(3);
            set.add(2); // This duplicate element will not be added

            System.out.println(set); // Output: [1, 2, 3]
        }
    }
Enter fullscreen mode Exit fullscreen mode

This example illustrates how duplicates are automatically prevented when using a Set in Java.

Top comments (0)