/** * Java Collections Framework > HashSetExample.java * * Use a HashSet to store objects and retrieve them quickly. HashSets are * faster than TreeSets at retrieval but do not store their elements in * sorted order. * @author Feihong Hsu */ import java.util.HashSet; // A container that supports quick retrieval import java.util.Iterator; // Useful for traversing a HashSet public class HashSetExample { // This method prints the elements of a given HashSet object. public static void printHashSet(HashSet hashSet) { System.out.print( "HashSet: " ); // Use an Iterator to print each element of the TreeSet. Iterator iterator = hashSet.iterator(); while (iterator.hasNext()) System.out.print( iterator.next() + ", " ); System.out.println(); } public static void main(String[] args) { HashSet hashSet = new HashSet(); // Add 5 objects to the HashSet. hashSet.add("Viking"); hashSet.add("Owari"); hashSet.add("Ainu"); hashSet.add("Incan"); hashSet.add("Eskimo"); // "HashSet: Incan, Ainu, Eskimo, Owari, Viking, " printHashSet(hashSet); // Remove the element from the HashSet which is a String with // value "Incan". hashSet.remove("Incan"); // "HashSet: Ainu, Eskimo, Owari, Viking, " printHashSet(hashSet); // Find out if the hashSet contains a String with value "Incan". System.out.print( "HashSet contains Incan? " ); System.out.println( hashSet.contains("Incan") ); // Prints false // Add another element to the HashSet. hashSet.add("Zulu"); // "HashSet: Zulu, Ainu, Eskimo, Owari, Viking, " printHashSet(hashSet); hashSet.clear(); // Remove all elements from the HashSet } }