Java Utility Library

Java.util.HashSet Class



Java HashSet Class

A HashSet class implements the Set interface, backed by the a Hashtable interface (actually a HashMap instance). This class makes no guarantees as to the iteration order of the set. It does not guarantee that the order will remain constant over time. The class permits the null element.

Class declaration

The declaration of java.util.HashSet class is:

public class HashSet<E>
  extends AbstractSet<E>
    implements Set<E>, Cloneable, Serializable

Here, E is the type of element maintained by the container.

Class Constructors

S.NConstructors & Description
1. HashSet()
Creates an empty HashSet with the default initial capacity (16) and load factor (0.75).
2. HashSet(int initialCapacity)
Creates an empty HashSet with the specified initial capacity and default load factor (0.75).
3. HashSet(int initialCapacity, float loadFactor)
Creates an empty HashSet with the specified initial capacity and the specified load factor.
4. HashSet(Map<? extends K,? extends V> m)
Creates a new HashSet containing the elements in the specified collection.

java.util.HashSet Methods

The java.util.HashSet class has a number of methods which are listed below:

Member Methods

S.NMethods & Description
1. boolean add(E element)
Adds the specified element in the set if it is not already present.
2. void clear()
Clears all elements of the set.
3. Object clone()
Returns a shallow copy of the HashSet instance.
4. boolean contains(Object obj)
Returns true if the set contains the specified element.
5. boolean isEmpty()
Checks whether the set is empty or not.
6. Iterator<E> iterator()
Returns an iterator over the elements in the set. The elements are returned in no particular order.
7. int size()
Returns the number of elements in the set.
8. boolean remove(Object obj)
Removes the specified element from the set, if it is present.
9. Spliterator<E> spliterator()
Creates a late-binding and fail-fast spliterator over the elements in the set.

Methods inherited

This class inherits the methods of following class:

  • java.lang.Object
  • java.util.AbstractCollection<E>
  • java.util.AbstractSet<E>

5