# Class WeakValueHashMap<K,V>

Object
AbstractMap<K,V>
WeakValueHashMap<K,V>

Type Parameters:
  `K` - the class of key elements.
  `V` - the class of value elements.

All Implemented Interfaces:
  `Map<K,V>`

public class WeakValueHashMap<K,V> extends AbstractMap<K,V>
A hashtable-based map implementation that uses weak references, leaving memory when an entry is not used anymore. An entry in a `WeakValueHashMap` will automatically be removed when its value is no longer in ordinary use. This class is similar to the standard `WeakHashMap` class, except that weak references apply to values rather than keys.

Note that this class is not a cache, because the entries are discarded as soon as the garbage collector determines that they are no longer in use. If caching service are wanted, or if concurrency are wanted, consider using `Cache` instead.

This class is convenient for avoiding the creation of duplicated elements, as in the example below:

    K key = ...
    V value;
    synchronized (map) {
        value = map.get(key);
        if (value == null) {
            value = ...; // Create the value here.
            map.put(key, value);
        }
    }

In the above example, the calculation of a new value needs to be fast because it is performed inside a synchronized statement blocking all other access to the map. This is okay if that particular `WeakValueHashMap` instance is not expected to be used in a highly concurrent environment.

`WeakValueHashMap` works with array keys as one would expect. For example, arrays of `int[]` are compared using the `Arrays​.equals(int[], int[])` method.

## Thread safety

The same `WeakValueHashMap` instance can be safely used by many threads without synchronization on the part of the caller. But if a sequence of two or more method calls need to appear atomic from other threads perspective, then the caller can synchronize on `this`.

Since:
  0.3
See Also:
  - `WeakHashMap`
  - `WeakHashSet`
  - `Cache`

- ## Nested Class Summary

  ### Nested classes/interfaces inherited from class AbstractMap

  `AbstractMap​.SimpleEntry<K,V>, AbstractMap​.SimpleImmutableEntry<K,V>`

- ## Constructor Summary

  Constructors
  Constructor
  Description
  `WeakValueHashMap(Class<K> keyType)`
  Creates a new `WeakValueHashMap`.
  `WeakValueHashMap(Class<K> keyType, boolean identity)`
  Creates a new `WeakValueHashMap`, optionally using reference-equality in place of object-equality.
  `WeakValueHashMap(Class<K> keyType, ToIntFunction<Object> hashFunction, BiPredicate<Object,Object> comparator)`
  Creates a new `WeakValueHashMap` using the given functions for computing hash code and equality.

- ## Method Summary

  Modifier and Type
  Method
  Description
  `void`
  `clear()`
  Removes all of the elements from this map.
  `V`
  `computeIfAbsent(K key, Function<? super K, ? extends V> creator)`
  Returns the value associated to the given key, computing the value if it does not exist.
  `boolean`
  `containsKey(Object key)`
  Returns `true` if this map contains a mapping for the specified key.
  `boolean`
  `containsValue(Object value)`
  Returns `true` if this map maps one or more keys to the specified value.
  `Set<Map​.Entry<K,V>>`
  `entrySet()`
  Returns a set view of the mappings contained in this map.
  `V`
  `get(Object key)`
  Returns the value to which this map maps the specified key.
  `V`
  `getOrDefault(Object key, V defaultValue)`
  Returns the value to which this map maps the specified key.
  `K`
  `intern(K key)`
  If this map contains the specified key, returns the instance contained in this map.
  `V`
  `put(K key, V value)`
  Associates the specified value with the specified key in this map.
  `V`
  `putIfAbsent(K key, V value)`
  Associates the specified value with the specified key in this map if no value were previously associated.
  `V`
  `remove(Object key)`
  Removes the mapping for this key from this map if present.
  `boolean`
  `remove(Object key, Object value)`
  Removes the entry for the specified key only if it is currently mapped to the specified value.
  `V`
  `replace(K key, V value)`
  Replaces the entry for the specified key only if it is currently mapped to some value.
  `boolean`
  `replace(K key, V oldValue, V newValue)`
  Replaces the entry for the specified key only if currently mapped to the specified value.
  `int`
  `size()`
  Returns the number of key-value mappings in this map.

  ### Methods inherited from class AbstractMap

  `clone, equals, hashCode, isEmpty, keySet, putAll, toString, values`

  ### Methods inherited from class Object

  `finalize, getClass, notify, notifyAll, wait, wait, wait`

  ### Methods inherited from interface Map

  `compute, computeIfPresent, forEach, merge, replaceAll`

- ## Constructor Details

  - ### WeakValueHashMap

    public WeakValueHashMap(Class<K> keyType)
    Creates a new `WeakValueHashMap`.
    Parameters:
      `keyType` - the type of keys in the map.

  - ### WeakValueHashMap

    public WeakValueHashMap(Class<K> keyType, boolean identity)
    Creates a new `WeakValueHashMap`, optionally using reference-equality in place of object-equality. If `identity` is `true`, then two keys `k1` and `k2` are considered equal if and only if `(k1 == k2)` instead of if `k1​.equals(k2)`.

    Reference-equality semantic is rarely used. See the `IdentityHashMap` class javadoc for a discussion about drawbacks and use cases when reference-equality semantic is useful.

    Parameters:
      `keyType` - the type of keys in the map.
      `identity` - `true` if the map shall use reference-equality in place of object-equality when comparing keys, or `false` for the standard behavior.
    Since:
      0.4

  - ### WeakValueHashMap

    public WeakValueHashMap(Class<K> keyType, ToIntFunction<Object> hashFunction, BiPredicate<Object,Object> comparator)
    Creates a new `WeakValueHashMap` using the given functions for computing hash code and equality. Commonly used functions are:

    Frequently used hash and comparison functions
    Desired behavior | Hash function | Comparator
    --- | --- | ---
    Standard (like `HashMap`) | `Object.hashCode()` | `Object.equals(Object)`
    Robust to arrays | `Utilities.deepHashCode(Object)` | `Objects.deepEquals(Object, Object)`
    Identity (like `IdentityHashMap`) | `System.identityHashCode(Object)` | `(o1,o2) -> o1 == o2`

    The functions do not need to be null-safe. `WeakValueHashMap` will never invoke `ToIntFunction​.applyAsInt(Object)` or `BiPredicate​.test(Object, Object)` with null arguments.
    Parameters:
      `keyType` - the type of keys in the map.
      `hashFunction` - the function to invoke for computing hash codes.
      `comparator` - the function to invoke for comparing two objects.
    Since:
      1.4

- ## Method Details

  - ### size

    public int size()
    Returns the number of key-value mappings in this map.
    Specified by:
      `size` in interface `Map<K,V>`
    Overrides:
      `size` in class `AbstractMap<K,V>`
    Returns:
      the number of entries in this map.

  - ### intern

    public K intern(K key)
    If this map contains the specified key, returns the instance contained in this map. Otherwise returns the given `key` instance.

    This method can be useful when the keys are potentially large objects. It allows to opportunistically share existing instances, a little bit like when using `WeakHashSet` except that this method does not add the given key to this map if not present.

    Parameters:
      `key` - key to look for in this map.
    Returns:
      the key instance in this map which is equal to the specified key, or `key` if none.
    Since:
      1.4

  - ### containsKey

    public boolean containsKey(Object key)
    Returns `true` if this map contains a mapping for the specified key. Null keys are considered never present.
    Specified by:
      `containsKey` in interface `Map<K,V>`
    Overrides:
      `containsKey` in class `AbstractMap<K,V>`
    Parameters:
      `key` - key whose presence in this map is to be tested.
    Returns:
      `true` if this map contains a mapping for the specified key.

  - ### containsValue

    public boolean containsValue(Object value)
    Returns `true` if this map maps one or more keys to the specified value. Null values are considered never present.
    Specified by:
      `containsValue` in interface `Map<K,V>`
    Overrides:
      `containsValue` in class `AbstractMap<K,V>`
    Parameters:
      `value` - value whose presence in this map is to be tested.
    Returns:
      `true` if this map maps one or more keys to the specified value.

  - ### get

    public V get(Object key)
    Returns the value to which this map maps the specified key. Returns `null` if the map contains no mapping for this key. Null keys are considered never present.
    Specified by:
      `get` in interface `Map<K,V>`
    Overrides:
      `get` in class `AbstractMap<K,V>`
    Parameters:
      `key` - key whose associated value is to be returned.
    Returns:
      the value to which this map maps the specified key.

  - ### getOrDefault

    public V getOrDefault(Object key, V defaultValue)
    Returns the value to which this map maps the specified key. Returns `defaultValue` if the map contains no mapping for this key. Null keys are considered never present.
    Parameters:
      `key` - key whose associated value is to be returned.
      `defaultValue` - the default mapping of the key.
    Returns:
      the value to which this map maps the specified key.
    Since:
      1.4

  - ### put

    public V put(K key, V value)
    Associates the specified value with the specified key in this map. The value is associated using a `WeakReference`.
    Specified by:
      `put` in interface `Map<K,V>`
    Overrides:
      `put` in class `AbstractMap<K,V>`
    Parameters:
      `key` - key with which the specified value is to be associated.
      `value` - value to be associated with the specified key.
    Returns:
      the previous value associated with specified key, or `null` if there was no mapping for the key.
    Throws:
      `NullPointerException` - if the key or the value is `null`.

  - ### putIfAbsent

    public V putIfAbsent(K key, V value)
    Associates the specified value with the specified key in this map if no value were previously associated. If another value is already associated to the given key, then the map is left unchanged and the current value is returned. Otherwise the specified value is associated to the key using a `WeakReference` and `null` is returned.
    Parameters:
      `key` - key with which the specified value is to be associated.
      `value` - value to be associated with the specified key.
    Returns:
      the current value associated with specified key, or `null` if there was no mapping for the key.
    Throws:
      `NullPointerException` - if the key or the value is `null`.
    Since:
      0.7

  - ### computeIfAbsent

    public V computeIfAbsent(K key, Function<? super K, ? extends V> creator)
    Returns the value associated to the given key, computing the value if it does not exist. This implementation is thread-safe.
    Parameters:
      `key` - key of the value to get.
      `creator` - function to invoke for creating the value if it does not already exist.
    Returns:
      value (potentially newly created) for the given key.
    Since:
      1.5

  - ### replace

    public V replace(K key, V value)
    Replaces the entry for the specified key only if it is currently mapped to some value.
    Parameters:
      `key` - key with which the specified value is to be associated.
      `value` - value to be associated with the specified key.
    Returns:
      the previous value associated with specified key, or `null` if there was no mapping for the key.
    Throws:
      `NullPointerException` - if the value is `null`.
    Since:
      1.2

  - ### replace

    public boolean replace(K key, V oldValue, V newValue)
    Replaces the entry for the specified key only if currently mapped to the specified value.
    Parameters:
      `key` - key with which the specified value is to be associated.
      `oldValue` - value expected to be associated with the specified key.
      `newValue` - value to be associated with the specified key.
    Returns:
      `true` if the value was replaced.
    Throws:
      `NullPointerException` - if the new value is `null`.
    Since:
      1.2

  - ### remove

    public V remove(Object key)
    Removes the mapping for this key from this map if present.
    Specified by:
      `remove` in interface `Map<K,V>`
    Overrides:
      `remove` in class `AbstractMap<K,V>`
    Parameters:
      `key` - key whose mapping is to be removed from the map.
    Returns:
      previous value associated with specified key, or `null` if there was no entry for the key.

  - ### remove

    public boolean remove(Object key, Object value)
    Removes the entry for the specified key only if it is currently mapped to the specified value.
    Parameters:
      `key` - key whose mapping is to be removed from the map.
      `value` - value expected to be associated with the specified key.
    Returns:
      `true` if the value was removed.
    Since:
      1.2

  - ### clear

    public void clear()
    Removes all of the elements from this map.
    Specified by:
      `clear` in interface `Map<K,V>`
    Overrides:
      `clear` in class `AbstractMap<K,V>`

  - ### entrySet

    public Set<Map.Entry<K,V>> entrySet()
    Returns a set view of the mappings contained in this map. Each element in this set is a `Map​.Entry`.
    Specified by:
      `entrySet` in interface `Map<K,V>`
    Specified by:
      `entrySet` in class `AbstractMap<K,V>`
    Returns:
      a set view of the mappings contained in this map.