Core JavaHashSet

Java HashSet Example

HashSet is a Java class that extends AbstractSet and implements the Set interface. It used to create collections by keeping an internal HashMap, but it does not permit the appearance of duplicate elements (as it is supposed to represent the mathematical “set” abstraction. We are going to take a look at how to use it and what you can accomplish through its methods.

 

 

 

1. HashSet Example

import java.util.HashSet;
import java.util.Iterator;


public class HashSetMain {

    public static void main(String[] args) {
        
        // Initialization of an empty HashSet,
        // which will contain String objects.
        HashSet set = new HashSet();
        
        // Adding elements to the Hashset.
        set.add("String 1");
        set.add("String 2");
        set.add("String 3");
        set.add("String 4");
        set.add("String 5");
        
        // Print all the elements in the set.
        System.out.println(set);
        
        // Get the number of elements (size) of the HashSet.
        System.out.println("Number of elements in the HashSet: " + set.size());
        
        // We can also check if a specific element exists in the HashSet.
        if (set.contains("String 10"))  // does not exist
            System.out.println("String 10 found!");
        else
            System.out.println("String 10 not found!");
        if (set.contains("String 3"))   // exists
            System.out.println("String 3 found!");
        else
            System.out.println("String 3 not found!");
        
        // We can get an iterator and manipulate all the objects
        // that are contained in the HashSet.
        Iterator setIterator = set.iterator();
        while (setIterator.hasNext()) {
            System.out.println("Iterated: " + setIterator.next());
        }
        
        // We can remove elements from the set.
        set.remove("String 1");
        set.remove("String 2");
        System.out.println(set);
        
        // We can remove everything from the set and empty it,
        // using the clear method. We can also check if it is empty or not.
        set.clear();
        System.out.println("Is HashSet empty after clear(): " + set.isEmpty());
    }
}

Output:

[String 4, String 3, String 5, String 2, String 1]
Number of elements in the HashSet: 5
String 10 not found!
String 3 found!
Iterated: String 4
Iterated: String 3
Iterated: String 5
Iterated: String 2
Iterated: String 1
[String 4, String 3, String 5]
Is HashSet empty after clear(): true

Keep in mind the fact that HashSet does not keep the order in which the elements were inserted. That’s why the iterator output is in a randomized order.

2. Method Explanation

Let’s take a look at the methods that are used in the example above.

  • add(Object obj): Add an object to the HashSet collection. If the element already exists, it will not be inserted again. It permits however to add a null value.
  • remove(Object obj): Remove an object, if it exists in the HashSet.
  • size(): Get the size (number of elements) of the HashSet.
  • contains(Object obj): Check if an object
  • clear(): Remove everything from the HashSet.
  • isEmpty(): Returns true if the HashSet is empty, false otherwise.
  • iterator(): Get an iterator which can be used to iterate over the contained objects.

3. Download the example

This was an example of HashSet in Java.

Download
You can download the full source code of this example here : HashSetExample

Ilias Koutsakis

Ilias has graduated from the Department of Informatics and Telecommunications of the National and Kapodistrian University of Athens. He is interested in all aspects of software engineering, particularly data mining, and loves the challenge of working with new technologies. He is pursuing the dream of clean and readable code on a daily basis.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button