Learnitweb

1. Introduction

In this tutorial we’ll discuss HashSet class of the Java Collections Framework.

HashSet class is in java.util package in java.base module. HashSet class implements the Set interface, backed by a hash table (actually a HashMap instance).

Following are the features of HashSet:

  • HashSet implements Set interface and therefore does not allow duplicate values.
  • HashSet allows the null element.
  • HashSet makes no guarantee as to the iteration order of the set. In particular, there is no guarantee that the iteration order will remain constant over time.
  • This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets.
  • HashSet implementation is not synchronized. If synchronization is the requirement, then the HashSet must be synchronized externally.
  • The iterators produced by this class’s iterator method are fail-fast. If the set is modified after the iterator is created, except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException.

Here is an example of HashSet:

import java.util.HashSet;

public class HashSetExample {
    public static void main(String args[]){
        HashSet<String> hashSet = new HashSet();
        hashSet.add("one");
        hashSet.add("two");
        hashSet.add("three");
        hashSet.add("one");
        hashSet.add("four");

        System.out.println(hashSet);
    }
}

Output

[four, one, two, three]

2. Creating HashSet

HashSet provides four overloaded constructors to create a HashSet.

HashSet()Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).
HashSet(int initialCapacity)Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and default load factor (0.75).
HashSet(int initialCapacity, float loadFactor)Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and the specified load factor.
HashSet(Collection<? extends E> c)Constructs a new set containing the elements in the specified collection.

3. Methods of HashSet

Following are methods of HashSet:

boolean add(E e)Adds the specified element to this set if it is not already present.
void clear()Removes all of the elements from this set.
Object clone()Returns a shallow copy of this HashSet instance: the elements themselves are not cloned.
boolean contains(Object o)Returns true if this set contains the specified element.
boolean isEmpty()Returns true if this set contains no elements.
Iterator<E> iterator()Returns an iterator over the elements in this set.
static <T> HashSet<T> newHashSet(int numElements)Creates a new, empty HashSet suitable for the expected number of elements.
boolean remove(Object o)Removes the specified element from this set if it is present.
int size()Returns the number of elements in this set (its cardinality).
Spliterator<E> spliterator()Creates a late-binding and fail-fast Spliterator over the elements in this set.
Object[] toArray()Returns an array containing all of the elements in this collection.
<T> T[] toArray(T[] a)Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.

4. Internal working of HashSet

HashSet is backed by a HashMap. HashMap has the property that its keys are unique. To understand in simple words, the values of the HashSet are the keys of the underlying HashMap.

The underlying code of HashSet can be used to understand the implementation. Following is the snippet from the HashSet class.

// Dummy value to associate with an Object in the backing Map
static final Object PRESENT = new Object();

public HashSet() {
   map = new HashMap<>();
}

When a value is inserted in the HashSet, you can think that the value is inserted as the key in the underlying HashMap. A dummy value PRESENT is inserted as the value of the key in the HashMap.

public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}

5. Examples

5.1 Add an element

add() method is used to add element to the HashSet.

hashSet.add("one");
hashSet.add("two");

5.2 Remove an element

remove() method is used to remove an element from the HashSet.

hashSet.remove("one");

5.3 Clear HashSet

The clear() method removes all of the elements from this set.

hashSet.clear();

5.4 Check if HashSet contains value

contains() method is used to check if the HashSet contains a particular value.

hashSet.contains("two")

6. Conclusion

In this tutorial, we’ve explored the HashSet class in Java, a powerful and efficient collection for storing unique elements. By leveraging the HashSet class, you can ensure that your collections maintain unique elements without the overhead of manual checks.