DEV Community

Code Green
Code Green

Posted on • Edited on

1

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️