Java Set add() example

In this guide, you will learn about the Set add() method in Java programming and how to use it with an example.

1. Set add() Method Overview


The add() method of the Java Set interface adds the specified element to this set if it is not already present.


boolean added = set.add(E e);


- E e: The element to be added to the set.

Key Points:

- The method returns true if this Set does not already contain the specified element.

- If the Set already contains the element, it remains unchanged and the method returns false.

- Null elements can be added to Set unless the specific set implementation prohibits it (like TreeSet).

- Since a Set is a collection that does not allow duplicate elements, repeated calls with the same element will not change the set.

2. Set add() Method Example

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

public class SetAddExample {
    public static void main(String[] args) {
        Set<String> colors = new HashSet<>();

        // Adding elements to the set
        boolean isAdded1 = colors.add("Red");
        boolean isAdded2 = colors.add("Green");
        boolean isAdded3 = colors.add("Blue");

        System.out.println("Is 'Red' added? : " + isAdded1);   // true
        System.out.println("Is 'Green' added? : " + isAdded2); // true
        System.out.println("Is 'Blue' added? : " + isAdded3);  // true

        // Trying to add a duplicate element
        boolean isAddedDuplicate = colors.add("Red");
        System.out.println("Is duplicate 'Red' added? : " + isAddedDuplicate); // false
        System.out.println("Set contents: " + colors); // [Red, Green, Blue]


Is 'Red' added? : true
Is 'Green' added? : true
Is 'Blue' added? : true
Is duplicate 'Red' added? : false
Set contents: [Red, Green, Blue]


In this example:

1. We create a HashSet of colors.

2. We add three colors: "Red", "Green", and "Blue" to the set. For each insertion, the method returns true indicating successful addition.

3. We then try to add "Red" again, which is a duplicate. The method returns false, and the set remains unchanged.

This example demonstrates the essence of a Set which is to store unique elements. The add() method provides a way to add new elements while ensuring the set's integrity by not allowing duplicates.

Related Java Set interface methods

Java Set add() example
Java Set contains() example
Java Set isEmpty() example
Java Set remove() example
Java Set size() example