java.util

Class LinkedHashMap<K,V>

Implemented Interfaces:
Cloneable, Map<K,V>, Serializable
Known Direct Subclasses:
LRUCache<K,V>

public class LinkedHashMap<K,V>
extends HashMap<K,V>

This class provides a hashtable-backed implementation of the Map interface, with predictable traversal order.

It uses a hash-bucket approach; that is, hash collisions are handled by linking the new node off of the pre-existing node (or list of nodes). In this manner, techniques such as linear probing (which can cause primary clustering) and rehashing (which does not fit very well with Java's method of precomputing hash codes) are avoided. In addition, this maintains a doubly-linked list which tracks either insertion or access order.

In insertion order, calling put adds the key to the end of traversal, unless the key was already in the map; changing traversal order requires removing and reinserting a key. On the other hand, in access order, all calls to put and get cause the accessed key to move to the end of the traversal list. Note that any accesses to the map's contents via its collection views and iterators do not affect the map's traversal order, since the collection views do not call put or get.

One of the nice features of tracking insertion order is that you can copy a hashtable, and regardless of the implementation of the original, produce the same results when iterating over the copy. This is possible without needing the overhead of TreeMap.

When using this constructor, you can build an access-order mapping. This can be used to implement LRU caches, for example. By overriding removeEldestEntry(Map.Entry), you can also control the removal of the oldest entry, and thereby do things like keep the map at a fixed size.

Under ideal circumstances (no collisions), LinkedHashMap offers O(1) performance on most operations (containsValue() is, of course, O(n)). In the worst case (all keys map to the same hash code -- very unlikely), most operations are O(n). Traversal is faster than in HashMap (proportional to the map size, and not the space allocated for the map), but other operations may be slower because of the overhead of the maintaining the traversal order list.

LinkedHashMap accepts the null key and null values. It is not synchronized, so if you need multi-threaded access, consider using:
Map m = Collections.synchronizedMap(new LinkedHashMap(...));

The iterators are fail-fast, meaning that any structural modification, except for remove() called on the iterator itself, cause the iterator to throw a ConcurrentModificationException rather than exhibit non-deterministic behavior.

Since:
1.4
See Also:
Object.hashCode(), Collection, Map, HashMap, TreeMap, Hashtable, Serialized Form

Nested Class Summary

Nested classes/interfaces inherited from class java.util.AbstractMap<K,V>

AbstractMap.SimpleEntry, AbstractMap.SimpleImmutableEntry

Constructor Summary

LinkedHashMap()
Construct a new insertion-ordered LinkedHashMap with the default capacity (11) and the default load factor (0.75).
LinkedHashMap(extends K, V> m)
Construct a new insertion-ordered LinkedHashMap from the given Map, with initial capacity the greater of the size of m or the default of 11.
LinkedHashMap(int initialCapacity)
Construct a new insertion-ordered LinkedHashMap with a specific inital capacity and default load factor of 0.75.
LinkedHashMap(int initialCapacity, float loadFactor)
Construct a new insertion-orderd LinkedHashMap with a specific inital capacity and load factor.
LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)
Construct a new LinkedHashMap with a specific inital capacity, load factor, and ordering mode.

Method Summary

void
clear()
Clears the Map so it has no keys.
boolean
containsValue(Object value)
Returns true if this HashMap contains a value o, such that o.equals(value).
V
get(Object key)
Return the value in this Map associated with the supplied key, or null if the key maps to nothing.
protected boolean
removeEldestEntry(java.util.Map.Entry eldest)
Returns true if this map should remove the eldest entry.

Methods inherited from class java.util.HashMap<K,V>

V>> entrySet, clear, clone, containsKey, containsValue, get, isEmpty, keySet, put, putAll, remove, size, values

Methods inherited from class java.util.AbstractMap<K,V>

V>> entrySet, clear, clone, containsKey, containsValue, equals, get, hashCode, isEmpty, keySet, put, putAll, remove, size, toString, values

Methods inherited from class java.lang.Object

clone, equals, extends Object> getClass, finalize, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Details

LinkedHashMap

public LinkedHashMap()
Construct a new insertion-ordered LinkedHashMap with the default capacity (11) and the default load factor (0.75).

LinkedHashMap

public LinkedHashMap(extends K,
                     V> m)
Construct a new insertion-ordered LinkedHashMap from the given Map, with initial capacity the greater of the size of m or the default of 11.

Every element in Map m will be put into this new HashMap, in the order of m's iterator.

Parameters:
m - a Map whose key / value pairs will be put into the new HashMap. NOTE: key / value pairs are not cloned in this constructor.
Throws:
NullPointerException - if m is null

LinkedHashMap

public LinkedHashMap(int initialCapacity)
Construct a new insertion-ordered LinkedHashMap with a specific inital capacity and default load factor of 0.75.
Parameters:
initialCapacity - the initial capacity of this HashMap (>= 0)
Throws:
IllegalArgumentException - if (initialCapacity < 0)

LinkedHashMap

public LinkedHashMap(int initialCapacity,
                     float loadFactor)
Construct a new insertion-orderd LinkedHashMap with a specific inital capacity and load factor.
Parameters:
initialCapacity - the initial capacity (>= 0)
loadFactor - the load factor (> 0, not NaN)
Throws:
IllegalArgumentException - if (initialCapacity < 0) || ! (loadFactor > 0.0)

LinkedHashMap

public LinkedHashMap(int initialCapacity,
                     float loadFactor,
                     boolean accessOrder)
Construct a new LinkedHashMap with a specific inital capacity, load factor, and ordering mode.
Parameters:
initialCapacity - the initial capacity (>=0)
loadFactor - the load factor (>0, not NaN)
accessOrder - true for access-order, false for insertion-order
Throws:
IllegalArgumentException - if (initialCapacity < 0) || ! (loadFactor > 0.0)

Method Details

clear

public void clear()
Clears the Map so it has no keys. This is O(1).
Specified by:
clear in interface Map<K,V>
Overrides:
clear in interface HashMap<K,V>

containsValue

public boolean containsValue(Object value)
Returns true if this HashMap contains a value o, such that o.equals(value).
Specified by:
containsValue in interface Map<K,V>
Overrides:
containsValue in interface HashMap<K,V>
Parameters:
value - the value to search for in this HashMap
Returns:
true if at least one key maps to the value

get

public V get(Object key)
Return the value in this Map associated with the supplied key, or null if the key maps to nothing. If this is an access-ordered Map and the key is found, this performs structural modification, moving the key to the newest end of the list. NOTE: Since the value could also be null, you must use containsKey to see if this key actually maps to something.
Specified by:
get in interface Map<K,V>
Overrides:
get in interface HashMap<K,V>
Parameters:
key - the key for which to fetch an associated value
Returns:
what the key maps to, if present
See Also:
put(Object, Object), containsKey(Object)

removeEldestEntry

protected boolean removeEldestEntry(java.util.Map.Entry eldest)
Returns true if this map should remove the eldest entry. This method is invoked by all calls to put and putAll which place a new entry in the map, providing the implementer an opportunity to remove the eldest entry any time a new one is added. This can be used to save memory usage of the hashtable, as well as emulating a cache, by deleting stale entries.

For example, to keep the Map limited to 100 entries, override as follows:

 private static final int MAX_ENTRIES = 100;
 protected boolean removeEldestEntry(Map.Entry eldest)
 {
   return size() > MAX_ENTRIES;
 }
 

Typically, this method does not modify the map, but just uses the return value as an indication to put whether to proceed. However, if you override it to modify the map, you must return false (indicating that put should leave the modified map alone), or you face unspecified behavior. Remember that in access-order mode, even calling get is a structural modification, but using the collections views (such as keySet) is not.

This method is called after the eldest entry has been inserted, so if put was called on a previously empty map, the eldest entry is the one you just put in! The default implementation just returns false, so that this map always behaves like a normal one with unbounded growth.

Parameters:
eldest - the eldest element which would be removed if this returns true. For an access-order map, this is the least recently accessed; for an insertion-order map, this is the earliest element inserted.
Returns:
true if eldest should be removed

LinkedHashMap.java -- a class providing hashtable data structure, mapping Object --> Object, with linked list traversal Copyright (C) 2001, 2002, 2005 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version.