HashSet

In this chapter you will learn:

  1. Get to know HashSet class

HashSet class

The HashSet extends AbstractSet and implements the Set interface.

It creates a collection that uses a hash table for storage. HashSet is a generic class that has this declaration:

class HashSet<E>

E specifies the type of objects that the set will hold.

A demonstration of a hashset with String elements unordered

import java.util.HashSet;
import java.util.Set;
//  j  a  v  a 2s  . c o m
public class Main {
  public static void main(String[] args) {
    Set<String> ss = new HashSet<String>();
    String[] fruits = { "apples", "pears", "grapes", "bananas", "kiwis", "pears", null };
    for (String fruit : fruits){
      ss.add(fruit);
    }
    for (String s : ss){
      System.out.print(s + " ");
    }
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to add elements to a HashSet
Home » Java Tutorial » Set
HashSet
HashSet element adding
HashSet element removing and clearing
HashSet clone
HashSet iterator
HashSet properties
TreeSet
TreeSet elements adding
TreeSet subSet
NavigableSet
LinkedHashSet