Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

472 Part II: The Java Library


LinkedHashMapadds only one method to those defined byHashMap. This method is
removeEldestEntry( )and it is shown here:

protected boolean removeEldestEntry(Map.Entry<K, V>e)

This method is called byput( )andputAll( ). The oldest entry is passed ine.By default, this
method returnsfalseand does nothing. However, if you override this method, then you can
have theLinkedHashMapremove the oldest entry in the map. To do this, have your override
returntrue. To keep the oldest entry, returnfalse.

The IdentityHashMap Class
IdentityHashMapextendsAbstractMapand implements theMapinterface. It is similar to
HashMapexcept that it uses reference equality when comparing elements.IdentityHashMap
is a generic class that has this declaration:

class IdentityHashMap<K, V>

Here,Kspecifies the type of key, andVspecifies the type of value. The API documentation
explicitly states thatIdentityHashMapis not for general use.

The EnumMap Class
EnumMapextendsAbstractMapand implementsMap. It is specifically for use with keys of
anenumtype. It is a generic class that has this declaration:

class EnumMap<K extends Enum<K>, V>

Here,Kspecifies the type of key, andVspecifies the type of value. Notice thatKmust extend
Enum<K>, which enforces the requirement that the keys must be of anenumtype.
EnumMapdefines the following constructors:

EnumMap(Class<K>kType)
EnumMap(Map<K,? extends V>m)
EnumMap(EnumMap<K,? extends V>em)

The first constructor creates an emptyEnumMapof typekType.The second creates an
EnumMapmap that contains the same entries asm.The third creates anEnumMapinitialized
with the values inem.
EnumMapdefines no methods of its own.

Comparators


BothTreeSetandTreeMapstore elements in sorted order. However, it is the comparator that
defines precisely what “sorted order” means. By default, these classes store their elements
by using what Java refers to as “natural ordering,” which is usually the ordering that you
would expect (A before B, 1 before 2, and so forth). If you want to order elements a different
way, then specify aComparatorwhen you construct the set or map. Doing so gives you the
ability to govern precisely how elements are stored within sorted collections and maps.
Comparatoris a generic interface that has this declaration:

interface Comparator<T>

Here,Tspecifies the type of objects being compared.
Free download pdf