Collections Framework - The Set Interface


A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.

Set Interface Hierarchy Diagram




Set Interface Class Diagram



Set Interface APIs/Methods

Below are the important Set interface methods with description:

  • boolean add(E e) - Adds the specified element to this set if it is not already present (optional operation).
  • boolean addAll(Collection<? extends E> c) - Adds all of the elements in the specified collection to this set if they're not already present (optional operation).
  • _void clear() _- Removes all of the elements from this set (optional operation).
  • boolean contains(Object o) - Returns true if this set contains the specified element.
  • boolean containsAll(Collection<?> c) - Returns true if this set contains all of the elements of the specified collection.
  • boolean equals(Object o) - Compares the specified object with this set for equality.
  • int hashCode() - Returns the hash code value for this set.
  • boolean isEmpty() - Returns true if this set contains no elements.
  • Iterator iterator() - Returns an iterator over the elements in this set.
  • boolean remove(Object o) - Removes the specified element from this set if it is present (optional operation).
  • boolean removeAll(Collection<?> c) - Removes from this set all of its elements that are contained in the specified collection (optional operation).
  • boolean retainAll(Collection<?> c) - Retains only the elements in this set that are contained in the specified collection (optional operation).
  • int size() - Returns the number of elements in this set (its cardinality).
  • default Spliterator spliterator() - Creates a Spliterator over the elements in this set.
  • _Object[] toArray() _- Returns an array containing all of the elements in this set.
  • T[] toArray(T[] a) - Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array.

Set Interface Simple Example


Let's create a simple example Set interface using the HashSet implementation class:

import java.util.HashSet;

import java.util.Set;

public class CreateHashSetExample {
    public static void main(String[] args) {
        // Creating a HashSet
     Set<String> daysOfWeek = new HashSet<>();

        // Adding new elements to the HashSet
        daysOfWeek.add("Monday");
        daysOfWeek.add("Tuesday");
        daysOfWeek.add("Wednesday");
        daysOfWeek.add("Thursday");
        daysOfWeek.add("Friday");
        daysOfWeek.add("Saturday");
        daysOfWeek.add("Sunday");

        // Adding duplicate elements will be ignored
        daysOfWeek.add("Monday");
        System.out.println(daysOfWeek);
    }
}
Output:
[Monday, Thursday, Friday, Sunday, Wednesday, Tuesday, Saturday]

Set Interface Implementations


The Java platform contains three general-purpose Set implementations: HashSetTreeSet, and LinkedHashSet.
  • HashSet, which stores its elements in a hash table, is the best-performing implementation; however, it makes no guarantees concerning the order of iteration.
  • TreeSet, which stores its elements in a red-black tree, orders its elements based on their values; it is substantially slower than HashSet.
  • LinkedHashSet, which is implemented as a hash table with a linked list running through it, orders its elements based on the order in which they were inserted into the set (insertion-order).
Below are the special-Purpose Set interface Implementations:
Following is an example to explain various class implementations of the Set interface.

Simple HashSet Implementation Example


package com.javaguides.collections.hashsetexamples;

import java.util.HashSet;

import java.util.Set;

public class CreateHashSetExample {
    public static void main(String[] args) {
        // Creating a HashSet
        Set < String > daysOfWeek = new HashSet < > ();

        // Adding new elements to the HashSet
        daysOfWeek.add("Monday");
        daysOfWeek.add("Tuesday");
        daysOfWeek.add("Wednesday");
        daysOfWeek.add("Thursday");
        daysOfWeek.add("Friday");
        daysOfWeek.add("Saturday");
        daysOfWeek.add("Sunday");

        // Adding duplicate elements will be ignored
        daysOfWeek.add("Monday");
        System.out.println(daysOfWeek);
    }
}
Output:
[Monday, Thursday, Friday, Sunday, Wednesday, Tuesday, Saturday]
Read more about HashSet class with examples at Guide to HashSet Class.

Simple LinkedHashSet Implementation Example


// Creating a HashSet
LinkedHashSet<String> daysOfWeek = new LinkedHashSet<>();

// Adding new elements to the HashSet
daysOfWeek.add("Monday");
daysOfWeek.add("Tuesday");
daysOfWeek.add("Wednesday");
daysOfWeek.add("Thursday");
daysOfWeek.add("Friday");
daysOfWeek.add("Saturday");
daysOfWeek.add("Sunday");

// Adding duplicate elements will be ignored
daysOfWeek.add("Monday");

System.out.println(daysOfWeek);
Output:
[Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday]
Read more about LinkedHashSet class with examples at Guide to LinkedHashSet Class.

Simple TreeSet Implementation Example

// Creating a TreeSet
TreeSet<String> fruits = new TreeSet<>();

// Adding new elements to a TreeSet
fruits.add("Banana");
fruits.add("Apple");
fruits.add("Pineapple");
fruits.add("Orange");

System.out.println("Fruits Set : " + fruits);

// Duplicate elements are ignored
fruits.add("Apple");
System.out.println("After adding duplicate element \"Apple\" : " + fruits);

// This will be allowed because it's in lowercase.
fruits.add("banana");
System.out.println("After adding \"banana\" : " + fruits);
Output:
Fruits Set : [Apple, Banana, Orange, Pineapple]
After adding duplicate element "Apple" : [Apple, Banana, Orange, Pineapple]
After adding "banana" : [Apple, Banana, Orange, Pineapple, banana]
Note that in this example, duplicate elements are ignored.
Read more about TreeSet class with examples at Guide to TreeSet Class.
Learn Java Collections Framework on Java Collections Tutorial

Comments