Set Interface in Java

In this tutorial, we will learn about Set Interface in Java and some of its implementation classes and their usage.

Set Interface in Java is present in java.util package, that represents a set of unique objects.

In other words, objects are unique in Set and the same object cannot occur more than once.

Set interface in Java is a subtype of the Java Collection, which means it inherits properties of the collection framework as well.

How Set is different from List Interface?

You must be aware of List Interface in Java, and maybe wondering what’s the difference?

So I would say there are two very big differences in both of the interfaces, wherein Set “every item must be unique” but you can add duplicates in List.

The second difference is about insertion order where Set is an unordered collection, it doesn’t maintain any order but in the case of List, the order of insertion of elements is maintained.

Therefore, if you want a unique collection of object you can go for Set Interface.

How to Declare Set in Java?

Let’s see how to create Set in Java:

Set<T> obj = new HashSet<>();

Here, “T” indicates the type of a Set. For example,

// create Integer type Set
Set<Integer> obj = new HashSet<>();

// create String type Set
Set<String> obj = new HashSet<>();

Set Interface in Java

Below is the exact code of Set Interface present in JDK. You can see what methods Set Interface in Java provides.

public interface Set<E> extends Collection<E> {
    int size();

    boolean isEmpty();

    boolean contains(Object var1);

    Iterator<E> iterator();

    Object[] toArray();

    <T> T[] toArray(T[] var1);

    boolean add(E var1);

    boolean remove(Object var1);

    boolean containsAll(Collection<?> var1);

    boolean addAll(Collection<? extends E> var1);

    boolean retainAll(Collection<?> var1);

    boolean removeAll(Collection<?> var1);

    void clear();

    boolean equals(Object var1);

    int hashCode();

    default Spliterator<E> spliterator() {
        return Spliterators.spliterator(this, 1);
    }
}

Any of its implementation class will leverage these methods.

Java Set Example:

Below is a sample program of Set in Java, using HashSet.

public class SetExample {

    public static void main(String[] args) {
        Set<Integer> obj = new HashSet<>();

        // adding elements
        obj.add(1);
        obj.add(2);
        obj.add(3);
        obj.add(4);
        obj.add(5);

        System.out.println("Values --> " + obj);

        // removing element
        obj.remove(3);

        System.out.println("Values After Removing--> " + obj);

    }
}

Output:

Values --> [1, 2, 3, 4, 5]
Values After Removing--> [1, 2, 4, 5]

Set Implementations:

You must be wondering why we have used HashSet in the above example.

It’s simple. Set is an interface, therefore, you need to instantiate a concrete implementation of the interface in order to use it.

Below are some general-purpose implementation classes that you can use to instantiate a Set.

  • java.util.HashSet
  • java.util.LinkedHashSet
  • java.util.TreeSet

1. HashSet

HashSet is backed by a HashMap. It is based on hashing principle and doesn’t maintain any order when you retrieve or iterate its object.

2. LinkedHashSet

LinkedHashSet is an ordered version of HashSet. Internally, it maintains a doubly-linked list. Therefore, if iteration order is needed, you can consider using LinkedHashSet.

3. TreeSet

TreeSet is an implementation of NavigableSet and SortedSet interface in Java and it uses a Tree for storage. By default, it maintains natural ascending order.

public class VectorExample {

    public static void main(String[] args) {
        // Creating a set using the TreeSet class
        Set<Integer> obj = new TreeSet<>();

        // Add elements to the set
        obj.add(8);
        obj.add(1);
        obj.add(4);
        obj.add(2);
        System.out.println("Printing Elements --> " + obj);

        // Access Elements using iterator()
        System.out.print("Printing Elements using iterator() --> ");
        Iterator<Integer> iterate = obj.iterator();
        while(iterate.hasNext()) {
            System.out.print(iterate.next());
            System.out.print(", ");
        }

    }
}

Output:

Printing Elements --> [1, 2, 4, 8]
Printing Elements using iterator() --> 1, 2, 4, 8,

NOTE: The performance of HashSet is better than LinkedHashSet and TreeSet. Also, TreeSet is faster than LinkedHashSet.

But, TreeSet is slower in case of insertion and removal because it has to sort the elements after each insertion and removal operation.

That’s it for the post, I hope you understand What is Set Interface in Java? and where you can use it. You can read next posts for better understanding of its implementations.

For Official Docs: Read Here

Vector Class in Java

Queue Interface in Java

Leave a Comment