/* * [TestHashSet.java] * * Summary: example use of java.util.HashSet. Sample code to TEST and demonstrate the use of HashSet. * * Copyright: (c) 2009-2017 Roedy Green, Canadian Mind Products, http://mindprod.com * * Licence: This software may be copied and used freely for any purpose but military. * http://mindprod.com/contact/nonmil.html * * Requires: JDK 1.8+ * * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/ * * Version History: * 1.0 2009-01-01 initial version */ package com.mindprod.example; import java.util.Arrays; import java.util.HashSet; import static java.lang.System.*; /** * example use of java.util.HashSet. Sample code to TEST and demonstrate the use of HashSet. * * @author Roedy Green, Canadian Mind Products * @version 1.0 2009-01-01 initial version * @since 2009-01-01 */ public final class TestHashSet { /** * Sample code to TEST and demonstrate the use of HashSet. * * @param args not used */ public static void main( String[] args ) { // create a new HashSet containing a list of all the legitimate state // and province abbreviations. HashSet regions = new HashSet<>( 149 /* capacity */, 0.75f /* loadfactor */ ); // add some elements, the abbreviations of states and provinces regions.add( "WA" ); regions.add( "NY" ); regions.add( "RI" ); regions.add( "BC" ); regions.add( "ON" ); // ... // look up a key in the HashSet to see if item is there boolean isLegit = regions.contains( "NY" ); // prints "true" out.println( isLegit ); // Note, there is no HashSet method to get you a reference to the // canonical unique String Object for each region String, // similar to what String.intern does. out.println( "enumerate all the elements in the regions HashSet, unordered" ); for ( String region : regions ) { // prints lines of the form NY // in effectively random order out.println( region ); } out.println( "enumerate all the elements in the regions HashSet, sorted" ); String[] sortedRegions = regions.toArray( new String[ regions.size() ] ); Arrays.sort( sortedRegions ); for ( String region : sortedRegions ) { // prints lines of the form NY // in alphabetical order out.println( region ); } } // end main }