The simplest way to create a cache using
is to extend it. Here is an example:
public class Cache extends
  LinkedHashMap
{
 private final int capacity;
 public Cache(int capacity)
 {
  super(capacity + 1, 1.1f, true);
  this.capacity = capacity;
 }
 protected boolean removeEldestEntry(Entry eldest)
 {
  return size() > capacity;
 }
}
Note that the constructor takes as an argument the maximum number of entries we want a Cache object to hold. The superclass constructor has three arguments: the initial capacity of the map, the load factor, and a boolean argument that tells the
constructor to keep entries in access order instead of the default insertion order. (See the
API documentation for a description of the initial capacity and load factor.) In this case we set the initial capacity to be one more than our required cache size - this is because new entries are added before any are removed, so for example if we want to hold 100 entries the cache will actually contain 101 for an instant when new data is added. Setting the load factor to 1.1 ensures that the rehashing mechanism of the underlying
class isn't triggered - this isn't a vital point but helps a little with efficiency at run-time.
method overrides a default implementation in
and is where we determine the policy for removing the oldest entry. In this case, we return
when the cache has more entries than our defined capacity.