// hashset_overview.jsl
import java.util.*;
public class Program
{
public static void main(String[] args)
{
// Populate a HashSet with three integers.
HashSet hs = new HashSet();
hs.add(new Integer(1));
hs.add(new Integer(2));
hs.add(new Integer(2));
hs.add(new Integer(3));
// Determine the size of the HashSet.
System.out.println("The HashSet contains " +
hs.size() + " elements.");
// Iterate over the contents of the HashSet.
Iterator iter = hs.iterator();
while (iter.hasNext())
{
System.out.println(iter.next().toString());
}
// Determine if an element exists, and if it does,
// remove it.
if (!hs.isEmpty())
{
Integer toRemove = new Integer(2);
if (hs.contains(toRemove))
{
if (hs.remove(toRemove))
{
System.out.println("Successfully removed element " +
toRemove.toString());
}
}
}
}
}
/*
Output:
The HashSet contains 3 elements.
1
2
3
Successfully removed element 2
*/