-
The java.util.HashSet
class in the Java standard class library is an implementation of the Set interface using a hash key. A hash key is an index that is calculated from a value by a hashing algorithm (see Lesson AB32, Hash-Coded Data Storage for more information on hash keys). The HashSet class implements the Set interface; therefore, Figure 28.1 describes HashSet’s methods as well.
Set<String> s = new HashSet<String>();
s.add( "Lynn" );
s.add( "Nancy" );
s.add( "David" );
s.add( "Lynn" );
System.out.println( "Size of set = " + s.size() );
Iterator<String> itr = s.iterator();
while( itr.hasNext() )
{
System.out.println( itr.next() );
}
Run Output:
Size of set = 3
Lynn
David
Nancy
-
Since a HashSet does not guarantee any particular order, the order of the output is not known. All we do know is that we will get all of the elements in the Set.
-
Hashing is a way for the data to be stored in an array in such a way that it can be retrieved very efficiently. Hashing is O(1) for add
, remove
, and contains
.