HashSet Class
Home ] Up ] Set Interface ] [ HashSet Class ] SortedSet Interface ] TreeSet Class ] TreeSet with Comparator ]

 

 

The HashSet class is an implementation of Set that uses a hash table:

Object
    AbstractCollection (implements Collection)
        AbstractSet (implements Set)
            HashSet

Here is our previous example that used ArrayList, changed to using HashSet.

The example only uses the Iterator approach to obtaining the elements from the collection, because there is no inherent ordering in a Set.

Note that I have added an additional call to add, which attempts to add a duplicate element for Frank.

package examples;
import java.util.HashSet;
import java.util.Iterator;
public class HashSetExample
{
  public static void main(String[] args)
  {
    HashSet set = new HashSet();
    set.add("Mary");
    set.add("Frank");
    set.add("Joe");
    set.add("Sylvia");
    set.add("Vanessa");
    set.add("Frank");   // Duplicate
    for (Iterator iter = set.iterator(); iter.hasNext(); )
    {
      String name = (String) iter.next(); // Note required cast
      System.out.println(name);
    }
  }
}

It outputs the following:

Vanessa
Joe
Frank
Mary
Sylvia

which shows that no duplicate element was added.  It also shows that the contents are returned in no particular order.

 

This page was last modified on 02 October, 2007