Java Collections – HashSet Example

The HashSet class implements the Set interface and uses a HashMap for storage. Ordering of the elements is not guaranteed to remain constant and it makes no guarantee about the iteration order. Like all Sets it does not allow any duplicates.

Big-O Notation

HashSet implementation provides constant-time O(1) performance for the basic operations at the index. Adding and deleting elements at the ends takes O(n). Compared to ArrayList there may be a slight penalty because HashSet is synchronized and ArrayList is not.

Creating a HashSet

HashSet<Car> cars = new HashSet<Car>();

Adding elements

Adding elements to the cars HashSet is done by using the add(Object obj) method.

Removing elements

Removing elements is just a matter of calling the overloaded method remove(Object obj).

cars.remove(taurus);
cars.remove(camarro);

Size of Collection

Returning the number of elements in a HashSet is as easy as calling the size() method.

cars.size();

Iterating through the Collection

Creating an iterator and looping through the collection is quite easy and straight forward.

// Loop through the collection of cars using iterator
Iterator<Car> iter = cars.iterator();
while (iter.hasNext()) {
  Car c = iter.next();
  System.out.format("%s (%s)n", c.getName(), c.getManufacturer());
}

Iterating through the Collection using foreach

Java 1.5 and above provides a foreach loop, which makes it much easier to iterate over the entire collection. This is my preferred way of doing it.

// Loop through the collection of cars using foreach
for (Car c : cars) {
   System.out.format("%s (%s)n", c.getName(), c.getManufacturer());
}

Full Program Listing (HashSetExample.java)

package com.avaldes.tutorials;

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

public class HashSetExample {

  public static void main(String[] args) {
    Set<Car> cars = new HashSet<Car>();
    
    System.out.println("Is HashSet Empty: " + cars.isEmpty()); 
    System.out.println("Initial cars size: " + cars.size()); 
    
    Car prius = new Car("Toyota", "Prius");
    Car pinto = new Car("Ford", "Pinto");
    Car taurus = new Car("Ford", "Taurus");
    Car maxima = new Car("Nissan", "Maxima");
    Car towncar= new Car("Lincoln", "Town Car");
    Car camaro = new Car("Chevrolet", "Carmaro");
    Car etzel = new Car("Ford", "Etzel");
    Car carrera = new Car("Porsche", "Carrera");
    Car grandprix = new Car("Pontiac", "Grand Prix");
    Car pilot = new Car("Honda", "Pilot");
    
    System.out.println("nAdding 4 elements to cars HashSet()...");
    cars.add(prius);
    cars.add(pinto);
    cars.add(taurus);
    cars.add(maxima);
    
    System.out.println("Check #1 cars size: " + cars.size()); 
    
    System.out.println("nAdding 2 more elements to cars HashSet()...");
    cars.add(towncar);
    cars.add(camaro);

    System.out.println("Check #2 cars size: " + cars.size()); 

    System.out.println("nAdding 4 more elements to cars HashSet()...");
    cars.add(etzel);
    cars.add(carrera);
    cars.add(grandprix);
    cars.add(pilot);

    System.out.println("Check #3 cars size: " + cars.size());
    
    // Sets do not allow duplicates
    System.out.println("nTrying to add duplicates, pinto and maxima...");  
    cars.add(pinto);
    cars.add(maxima);
    
    System.out.println("Check #4 cars size: " + cars.size()); 

    System.out.println("nRemoving 2 elements, towncar and grandprix...");  
    cars.remove(towncar);
    cars.remove(grandprix);
    System.out.println("Check #5 cars size: " + cars.size()); 
    
    // Loop through the collection of cars</span>
    /*Iterator<Car> iter = cars.iterator();
    while (iter.hasNext()) {
      Car c = iter.next();
      System.out.format("%s (%s)n", c.getName(), c.getManufacturer());
    } */
    
    System.out.println("nDisplaying the full list of cars...");
    for (Car c : cars) {
      System.out.format("%s (%s)n", c.getName(), c.getManufacturer());
    }
  }
}

Full Program Listing (Car.java)

package com.avaldes.tutorials;

public class Car {
  private String Manufacturer;
  private String name;
  
  public Car(String manufacturer, String name) {
    setManufacturer(manufacturer);
    setName(name);
  }

  public String getManufacturer() {
    return Manufacturer;
  }

  public void setManufacturer(String manufacturer) {
    Manufacturer = manufacturer;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}

Output

Is HashSet Empty: true
Initial cars size: 0

Adding 4 elements to cars HashSet()...
Check #1 cars size: 4

Adding 2 more elements to cars HashSet()...
Check #2 cars size: 6

Adding 4 more elements to cars HashSet()...
Check #3 cars size: 10

Trying to add duplicates, pinto and maxima...
Check #4 cars size: 10

Removing 2 elements, towncar and grandprix...
Check #5 cars size: 8

Displaying the full list of cars...
Carrera (Porsche)
Carmaro (Chevrolet)
Pinto (Ford)
Pilot (Honda)
Etzel (Ford)
Prius (Toyota)
Taurus (Ford)
Maxima (Nissan)

Other Related Posts

Map Examples

List Examples

Set Examples

Please Share Us on Social Media

Facebooktwitterredditpinterestlinkedinmail

Leave a Reply

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