Class UnorderedMap<K,​V>

java.lang.Object
squidpony.squidmath.UnorderedMap<K,​V>
All Implemented Interfaces:
Serializable, Cloneable, Map<K,​V>

public class UnorderedMap<K,​V>
extends Object
implements Map<K,​V>, Serializable, Cloneable
A generic unordered hash map; generally prefer HashMap unless you need array keys. Originally from fastutil as Object2ObjectOpenCustomHashMap but modified to support SquidLib's CrossHash.IHasher interface for custom hashing instead of fastutil's Strategy interface.
Instances of this class use a hash table to represent a map. The table is filled up to a specified load factor, and then doubled in size to accommodate new entries. If the table is emptied below one fourth of the load factor, it is halved in size. However, halving is not performed when deleting entries from an iterator, as it would interfere with the iteration process.
Note that clear() does not modify the hash table size. Rather, a family of trimming methods lets you control the size of the table; this is particularly useful if you reuse instances of this class.
You can pass a CrossHash.IHasher instance such as CrossHash.generalHasher as an extra parameter to most of this class' constructors, which allows the OrderedMap to use arrays (usually primitive arrays) as keys. If you expect only one type of array, you can use an instance like CrossHash.intHasher to hash int arrays, or the aforementioned generalHasher to hash most kinds of arrays (it can't handle most multi-dimensional arrays well). If you aren't using arrays as keys, you don't need to give an IHasher to the constructor and can ignore this feature most of the time. However, the default IHasher this uses if none is specified performs a small but significant "mixing" step to make the default generated hashCode() implementation many classes use into a higher-quality random-like value. This isn't always optimal; if you plan to insert 1000 sequential Integer keys with some small amount of random Integers after them, then the mixing actually increases the likelihood of a collision and takes time to calculate. You could use a very simple IHasher in that case, relying on the fact that only Integers will be added:
 new CrossHash.IHasher() {
     public int hash(Object data) { return (int)data; }
     public boolean areEqual(Object left, Object right) { return Objects.equals(left, right); }
 };
 
This is just one example of a case where a custom IHasher can be useful for performance reasons; there are also cases where an IHasher is needed to enforce hashing by identity or by value, which affect program logic. Note that the given IHasher is likely to be sub-optimal for many situations with Integer keys, and you may want to try a few different approaches if you know OrderedMap is a bottleneck in your application. If the IHasher is a performance problem, it will be at its worst if the OrderedMap needs to resize, and thus rehash, many times; this won't happen if the capacity is set correctly when the OrderedMap is created (with the capacity equal to or greater than the maximum number of entries that will be added).
Thank you, Sebastiano Vigna, for making FastUtil available to the public with such high quality.
See https://github.com/vigna/fastutil for the original library.
Author:
Sebastiano Vigna (responsible for all the hard parts), Tommy Ettinger (mostly responsible for squashing several layers of parent classes into one monster class)
See Also:
Serialized Form
  • Field Details

  • Constructor Details

    • UnorderedMap

      public UnorderedMap​(int expected, float f)
      Creates a new OrderedMap.

      The actual table size will be the least power of two greater than expected/f.

      Parameters:
      expected - the expected number of elements in the hash set.
      f - the load factor.
    • UnorderedMap

      public UnorderedMap​(int expected)
      Creates a new OrderedMap with 0.75f as load factor.
      Parameters:
      expected - the expected number of elements in the OrderedMap.
    • UnorderedMap

      public UnorderedMap()
      Creates a new OrderedMap with initial expected 16 entries and 0.75f as load factor.
    • UnorderedMap

      public UnorderedMap​(Map<? extends K,​? extends V> m, float f)
      Creates a new OrderedMap copying a given one.
      Parameters:
      m - a Map to be copied into the new OrderedMap.
      f - the load factor.
    • UnorderedMap

      public UnorderedMap​(Map<? extends K,​? extends V> m)
      Creates a new OrderedMap with 0.75f as load factor copying a given one.
      Parameters:
      m - a Map to be copied into the new OrderedMap.
    • UnorderedMap

      public UnorderedMap​(K[] keyArray, V[] valueArray, float f)
      Creates a new OrderedMap using the elements of two parallel arrays.
      Parameters:
      keyArray - the array of keys of the new OrderedMap.
      valueArray - the array of corresponding values in the new OrderedMap.
      f - the load factor.
      Throws:
      IllegalArgumentException - if k and v have different lengths.
    • UnorderedMap

      public UnorderedMap​(Collection<K> keyColl, Collection<V> valueColl)
      Creates a new OrderedMap using the elements of two parallel arrays.
      Parameters:
      keyColl - the collection of keys of the new OrderedMap.
      valueColl - the collection of corresponding values in the new OrderedMap.
      Throws:
      IllegalArgumentException - if k and v have different lengths.
    • UnorderedMap

      public UnorderedMap​(Collection<K> keyColl, Collection<V> valueColl, float f)
      Creates a new OrderedMap using the elements of two parallel arrays.
      Parameters:
      keyColl - the collection of keys of the new OrderedMap.
      valueColl - the collection of corresponding values in the new OrderedMap.
      f - the load factor.
      Throws:
      IllegalArgumentException - if k and v have different lengths.
    • UnorderedMap

      public UnorderedMap​(K[] keyArray, V[] valueArray)
      Creates a new OrderedMap with 0.75f as load factor using the elements of two parallel arrays.
      Parameters:
      keyArray - the array of keys of the new OrderedMap.
      valueArray - the array of corresponding values in the new OrderedMap.
      Throws:
      IllegalArgumentException - if k and v have different lengths.
    • UnorderedMap

      public UnorderedMap​(int expected, float f, CrossHash.IHasher hasher)
      Creates a new OrderedMap.

      The actual table size will be the least power of two greater than expected/f.

      Parameters:
      expected - the expected number of elements in the hash set.
      f - the load factor.
      hasher - used to hash items; typically only needed when K is an array, where CrossHash has implementations
    • UnorderedMap

      public UnorderedMap​(int expected, CrossHash.IHasher hasher)
      Creates a new OrderedMap with 0.75f as load factor.
      Parameters:
      expected - the expected number of elements in the OrderedMap.
      hasher - used to hash items; typically only needed when K is an array, where CrossHash has implementations
    • UnorderedMap

      public UnorderedMap​(CrossHash.IHasher hasher)
      Creates a new OrderedMap with initial expected 16 entries and 0.75f as load factor.
    • UnorderedMap

      public UnorderedMap​(Map<? extends K,​? extends V> m, float f, CrossHash.IHasher hasher)
      Creates a new OrderedMap copying a given one.
      Parameters:
      m - a Map to be copied into the new OrderedMap.
      f - the load factor.
      hasher - used to hash items; typically only needed when K is an array, where CrossHash has implementations
    • UnorderedMap

      public UnorderedMap​(Map<? extends K,​? extends V> m, CrossHash.IHasher hasher)
      Creates a new OrderedMap with 0.75f as load factor copying a given one.
      Parameters:
      m - a Map to be copied into the new OrderedMap.
      hasher - used to hash items; typically only needed when K is an array, where CrossHash has implementations
    • UnorderedMap

      public UnorderedMap​(K[] keyArray, V[] valueArray, float f, CrossHash.IHasher hasher)
      Creates a new OrderedMap using the elements of two parallel arrays.
      Parameters:
      keyArray - the array of keys of the new OrderedMap.
      valueArray - the array of corresponding values in the new OrderedMap.
      f - the load factor.
      hasher - used to hash items; typically only needed when K is an array, where CrossHash has implementations
      Throws:
      IllegalArgumentException - if k and v have different lengths.
    • UnorderedMap

      public UnorderedMap​(K[] keyArray, V[] valueArray, CrossHash.IHasher hasher)
      Creates a new OrderedMap with 0.75f as load factor using the elements of two parallel arrays.
      Parameters:
      keyArray - the array of keys of the new OrderedMap.
      valueArray - the array of corresponding values in the new OrderedMap.
      hasher - used to hash items; typically only needed when K is an array, where CrossHash has implementations
      Throws:
      IllegalArgumentException - if k and v have different lengths.
  • Method Details

    • defaultReturnValue

      public void defaultReturnValue​(V rv)
    • defaultReturnValue

    • putAll

      public void putAll​(K[] keyArray, V[] valueArray)
      Puts the first key in keyArray with the first value in valueArray, then the second in each and so on. The entries are all appended to the end of the iteration order, unless a key was already present. Then, its value is changed at the existing position in the iteration order. If the lengths of the two arrays are not equal, this puts a number of entries equal to the lesser length. If either array is null, this returns without performing any changes.
      Parameters:
      keyArray - an array of K keys that should usually have the same length as valueArray
      valueArray - an array of V values that should usually have the same length as keyArray
    • putAll

      public void putAll​(Map<? extends K,​? extends V> m)
      Puts all key-value pairs in the Map m into this OrderedMap. The entries are all appended to the end of the iteration order, unless a key was already present. Then, its value is changed at the existing position in the iteration order. This can take any kind of Map, including unordered HashMap objects; if the Map does not have stable ordering, the order in which entries will be appended is not stable either. For this reason, OrderedMap, LinkedHashMap, and TreeMap (or other SortedMap implementations) will work best when order matters.
      Specified by:
      putAll in interface Map<K,​V>
      Parameters:
      m - a Map that should have the same or compatible K key and V value types; OrderedMap and TreeMap work best
    • put

      public V put​(K k, V v)
      Specified by:
      put in interface Map<K,​V>
    • shiftKeys

      protected final void shiftKeys​(int pos)
      Shifts left entries with the specified hash code, starting at the specified position, and empties the resulting free entry.
      Parameters:
      pos - a starting position.
    • remove

      public V remove​(Object k)
      Specified by:
      remove in interface Map<K,​V>
    • get

      public V get​(Object k)
      Specified by:
      get in interface Map<K,​V>
    • getOrDefault

      public V getOrDefault​(Object k, V defaultValue)
      Specified by:
      getOrDefault in interface Map<K,​V>
    • positionOf

      protected int positionOf​(Object k)
    • containsKey

      public boolean containsKey​(Object k)
      Specified by:
      containsKey in interface Map<K,​V>
    • containsValue

      public boolean containsValue​(Object v)
      Specified by:
      containsValue in interface Map<K,​V>
    • clear

      public void clear()
      Specified by:
      clear in interface Map<K,​V>
    • size

      public int size()
      Specified by:
      size in interface Map<K,​V>
    • isEmpty

      public boolean isEmpty()
      Specified by:
      isEmpty in interface Map<K,​V>
    • entrySet

      public Set<Map.Entry<K,​V>> entrySet()
      Specified by:
      entrySet in interface Map<K,​V>
    • keySet

      public Set<K> keySet()
      Specified by:
      keySet in interface Map<K,​V>
    • values

      public Collection<V> values()
      Specified by:
      values in interface Map<K,​V>
    • valuesAsList

    • trim

      public boolean trim()
      Rehashes the map, making the table as small as possible.

      This method rehashes the table to the smallest size satisfying the load factor. It can be used when the set will not be changed anymore, so to optimize access speed and size.

      If the table size is already the minimum possible, this method does nothing.

      Returns:
      true if there was enough memory to trim the map.
      See Also:
      trim(int)
    • trim

      public boolean trim​(int n)
      Rehashes this map if the table is too large.

      Let N be the smallest table size that can hold max(n,size()) entries, still satisfying the load factor. If the current table size is smaller than or equal to N, this method does nothing. Otherwise, it rehashes this map in a table of size N.

      This method is useful when reusing maps. Clearing a map leaves the table size untouched. If you are reusing a map many times, you can call this method with a typical size to avoid keeping around a very large table just because of a few large transient maps.

      Parameters:
      n - the threshold for the trimming.
      Returns:
      true if there was enough memory to trim the map.
      See Also:
      trim()
    • rehash

      protected void rehash​(int newN)
      Rehashes the map.

      This method implements the basic rehashing strategy, and may be overriden by subclasses implementing different rehashing strategies (e.g., disk-based rehashing). However, you should not override this method unless you understand the internal workings of this class.

      Parameters:
      newN - the new size
    • clone

      public UnorderedMap<K,​V> clone()
      Returns a deep copy of this map.

      This method performs a deep copy of this OrderedMap; the data stored in the map, however, is not cloned. Note that this makes a difference only for object keys.

      Overrides:
      clone in class Object
      Returns:
      a deep copy of this map.
    • hashCode

      public int hashCode()
      Returns a hash code for this map. This method overrides the generic method provided by the superclass. Since equals() is not overriden, it is important that the value returned by this method is the same value as the one returned by the overriden method.
      Specified by:
      hashCode in interface Map<K,​V>
      Overrides:
      hashCode in class Object
      Returns:
      a hash code for this map.
    • hash64

      public long hash64()
    • maxFill

      public static int maxFill​(int n, float f)
      Returns the maximum number of entries that can be filled before rehashing.
      Parameters:
      n - the size of the backing array.
      f - the load factor.
      Returns:
      the maximum number of entries before rehashing.
    • arraySize

      public static int arraySize​(int expected, float f)
      Returns the least power of two smaller than or equal to 230 and larger than or equal to Math.ceil( expected / f ). re
      Parameters:
      expected - the expected number of elements in a hash table.
      f - the load factor.
      Returns:
      the minimum possible size for a backing array.
      Throws:
      IllegalArgumentException - if the necessary size is larger than 230.
    • toString

      public String toString()
      Overrides:
      toString in class Object
    • equals

      public boolean equals​(Object o)
      Specified by:
      equals in interface Map<K,​V>
      Overrides:
      equals in class Object
    • getMany

      public List<V> getMany​(Collection<K> keys)
    • putIfAbsent

      public V putIfAbsent​(K key, V value)
      If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
      Specified by:
      putIfAbsent in interface Map<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 the specified key, or null if there was no mapping for the key. (A null return can also indicate that the map previously associated null with 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.
      Specified by:
      remove in interface Map<K,​V>
      Parameters:
      key - key with which the specified value is associated
      value - value expected to be associated with the specified key
      Returns:
      true if the value was removed
    • 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. The position in the iteration order is retained.
      Specified by:
      replace in interface Map<K,​V>
      Parameters:
      key - key with which the specified value is 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
    • replace

      public V replace​(K key, V value)
      Replaces the entry for the specified key only if it is currently mapped to some value. Preserves the existing key's position in the iteration order.
      Specified by:
      replace in interface Map<K,​V>
      Parameters:
      key - key with which the specified value is associated
      value - value to be associated with the specified key
      Returns:
      the previous value associated with the specified key, or null if there was no mapping for the key. (A null return can also indicate that the map previously associated null with the key.)
    • putPairs

      public UnorderedMap<K,​V> putPairs​(K k0, V v0, Object... rest)
      Given alternating key and value arguments in pairs, puts each key-value pair into this OrderedMap as if by calling put(Object, Object) repeatedly for each pair. This mimics the parameter syntax used for makeMap(Object, Object, Object...), and can be used to retain that style of insertion after an OrderedMap has been instantiated.
      Parameters:
      k0 - the first key to add
      v0 - the first value to add
      rest - an array or vararg of keys and values in pairs; should contain alternating K, V, K, V... elements
      Returns:
      this, after adding all viable key-value pairs given
    • makeMap

      public static <K,​ V> UnorderedMap<K,​V> makeMap​(K k0, V v0, Object... rest)
      Makes an OrderedMap (OM) with the given load factor (which should be between 0.1 and 0.9), key and value types inferred from the types of k0 and v0, and considers all remaining parameters key-value pairs, casting the Objects at positions 0, 2, 4... etc. to K and the objects at positions 1, 3, 5... etc. to V. If rest has an odd-number length, then it discards the last item. If any pair of items in rest cannot be cast to the correct type of K or V, then this inserts nothing for that pair. This is similar to the makeOM method in the Maker class, but does not allow setting the load factor (since that extra parameter can muddle how javac figures out which generic types the map should use), nor does it log debug information if a cast fails. The result should be the same otherwise.
      This is named makeMap to indicate that it expects key and value parameters, unlike a Set or List. This convention may be extended to other data structures that also have static methods for instantiation.
      Type Parameters:
      K - the type of keys in the returned OrderedMap; if not specified, will be inferred from k0
      V - the type of values in the returned OrderedMap; if not specified, will be inferred from v0
      Parameters:
      k0 - the first key; used to infer the types of other keys if generic parameters aren't specified.
      v0 - the first value; used to infer the types of other values if generic parameters aren't specified.
      rest - an array or vararg of keys and values in pairs; should contain alternating K, V, K, V... elements
      Returns:
      a freshly-made OrderedMap with K keys and V values, using k0, v0, and the contents of rest to fill it
    • makeMap

      public static <K,​ V> UnorderedMap<K,​V> makeMap()
      Makes an empty OrderedMap (OM); needs key and value types to be specified in order to work. For an empty OrderedMap with String keys and Coord values, you could use Maker.<String, Coord>makeOM(). Using the new keyword is probably just as easy in this case; this method is provided for completeness relative to makeMap() with 2 or more parameters.
      Type Parameters:
      K - the type of keys in the returned OrderedMap; cannot be inferred and must be specified
      V - the type of values in the returned OrderedMap; cannot be inferred and must be specified
      Returns:
      an empty OrderedMap with the given key and value types.