Java The Complete Reference, Seventh Edition

(Greg DeLong) #1
It is important to note thatHashSetdoes not guarantee the order of its elements, because
the process of hashing doesn’t usually lend itself to the creation of sorted sets. If you need
sorted storage, then another collection, such asTreeSet, is a better choice.
Here is an example that demonstratesHashSet:

// Demonstrate HashSet.
import java.util.*;

class HashSetDemo {
public static void main(String args[]) {
// Create a hash set.
HashSet<String> hs = new HashSet<String>();

// Add elements to the hash set.
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");

System.out.println(hs);
}
}

The following is the output from this program:

[D, A, F, C, B, E]

As explained, the elements are not stored in sorted order, and the precise output may vary.

The LinkedHashSet Class


TheLinkedHashSetclass extendsHashSetand adds no members of its own. It is a generic
class that has this declaration:

class LinkedHashSet<E>

Here,Especifies the type of objects that the set will hold. Its constructors parallel those in
HashSet.
LinkedHashSetmaintains a linked list of the entries in the set, in the order in which they
were inserted. This allows insertion-order iteration over the set. That is, when cycling through
aLinkedHashSetusing an iterator, the elements will be returned in the order in which they
were inserted. This is also the order in which they are contained in the string returned by
toString( )when called on aLinkedHashSetobject. To see the effect ofLinkedHashSet, try
substitutingLinkedHashSetforHashSetin the preceding program. The output will be

[B, A, D, E, C, F]

which is the order in which the elements were inserted.

454 Part II: The Java Library

Free download pdf