Class FixedSizeCache<K,V>

java.lang.Object
com.jagrosh.jdautilities.commons.utils.FixedSizeCache<K,V>

public class FixedSizeCache<K,V> extends Object
A simple first-in-first-out key-value storage that uses a HashMap to store keys and values while simultaneously registering the keys to an array to maintain a specified maximum capacity.

As new elements are inserted into the cache, older ones may be removed as a result of the cache being at the maximum capacity set at instantiation.

Since:
1.3
Author:
Michael Ritter
  • Constructor Details

    • FixedSizeCache

      public FixedSizeCache(int size)
      Constructs a new FixedSizeCache with a set maximum capacity.

      This entity runs on the basis of "first-in-first-out", meaning that elements inserted into the newly constructed cache will remove the oldest ones if the maximum size is already being occupied.

      Parameters:
      size - The size of the FixedSizeCache to be created.
  • Method Details

    • add

      public void add(K key, V value)
      Adds a key and pairs it with a value.

      If this FixedSizeCache is already at maximum occupation, this will remove the oldest element.

      NOTE: Any inner workings of HashMap#put(Object, Object) still apply when using this method!
      It is recommended anyone using this consult the documentation for HashMap.

      Parameters:
      key - The key to pair with the value
      value - The value to pair with the key
      See Also:
    • contains

      public boolean contains(K key)
      Checks if this FixedSizeCache contains a key.

      NOTE: Any inner workings of HashMap#containsKey(Object) still apply when using this method!
      It is recommended anyone using this consult the documentation for HashMap.

      Parameters:
      key - The key to check for
      Returns:
      true if the FixedSizeCache contains a key, else false
      See Also:
    • get

      public V get(K key)
      Retrieves a value from this FixedSizeCache corresponding to the specified key, or null if there is no corresponding value to be retrieved.

      NOTE: Any inner workings of HashMap#get(Object) still apply when using this method!
      It is recommended anyone using this consult the documentation for HashMap.

      Parameters:
      key - The key to retrieve a value for
      Returns:
      A value corresponding to the provided key, or null if there was no value to get.
      See Also: