Additional Hash Table and Set ImplementationsThe package java.util includes several additional classes that implement the Map and Set interfaces. I'll briefly overview some of these. Consult the Java API documentation for the package java.util for more details on their use. EnumSetYou learned about EnumMap in Lesson 6. The EnumSet class works a little differently. It is defined as an abstract class. You create an instance of an (unnamed) EnumSet subclass by calling one of almost a dozen EnumSet class methods. I summarize these factory methods in Table 9.1.
Using EnumSet, you can simplify the ReportCardTest method testKeys (above) as follows:
TreeSet and TreeMapA TreeSet maintains the order of its elements based on their natural sorting order (that you define using Comparable) or a sort order you define using a Comparator object. A TreeMap maintains the order of its keys in a similar manner. As an example, you might choose to ensure that the report card messages stay ordered by student grade. You pay for this behavior. Instead of almost immediate insertion and retrieval time, as you expect when using a HashMap or HashSet, operation times increase logarithmically as the size of the collection increases. LinkedHashSet and LinkedHashMapA LinkedHashSet maintains the order of its elements chronologically: It remembers the order in which you inserted elements. It does so by maintaining a linked list behind the scenes. Its performance is comparable to that of HashSet: add, contains, and remove all execute in constant time but with slightly more overhead. Iterating against a LinkedHashSet can actually execute faster than iterating against a regular HashSet. The Map analog is LinkedHashMap. IdentityHashMapAn IdentityHashMap uses reference equality (==) to compare keys instead of equality (equals). You would use this Map implementation if you needed keys to represent unique instances. This class is not a general-purpose map implementation since it violates the contract that Maps should compare keys using equals. |
Monday, October 19, 2009
Additional Hash Table and Set Implementations
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment