HashSet in Java

HastSet is one of the classes available with collections package and it extends the AbstractSet and implements the Set interface. This uses the hash table for storing the values. Hash table internally using hashing mechanism to store the values. In the hashing technique, information is uniquely identified using the hash code. HashSet supports four constructors. This allows the null values.

  • Default Constructor – HashSet()
  • One with initial set of collections as parameter – HashSet(Collection c)
  • Creating HashSet with initial capacity – HashSet(int capacity)
  • Initial capacity and the fill ration to grow the capacity after certain elements inserted – HashSet(int capacity, float fillRatio)

HashSet Methods

The following are the list of methods defined in the HashSet class. This apart from the inherited methods from the parent classes.

  • boolean add(Object obj) –> Adds the element if it is not aleady there
  • void clear() –> Clears all the element from the set
  • Object clone() –> Creates a shallow copy of this HashSet instance
  • boolean contains(Object obj) –> Checks and returns true if this set contains the specified element
  • boolean isEmpty() –> Returns true if this set is empty
  • Iterator iterator() –> Returns an iterator over the elements in this set
  • boolean remove(Object obj) –> Removes the specified element from this set if it is present
  • int size() –> Returns the number of elements in this set (its cardinality)

HashSet Example

package javabeat.net.core;

import java.util.HashSet;

public class HashSetDemo {
	public static void main(String args[]) {
		// create a hash set with default constructor
		HashSet<String> hashSet = new HashSet<String>();
		// add elements to the hash set
		hashSet.add("Element 1");
		hashSet.add("Element 2");
		hashSet.add("Element 3");

Output of the above example will be:

[Element 3, Element 2, Element 1]

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!