Module hash4j

Interface HashFunnel<T>

Type Parameters:
T - the type
Functional Interface:
This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

@FunctionalInterface public interface HashFunnel<T>
A hash funnel describing how objects of a given type are put into a HashSink.

When hashing a Java object, the information of all its fields need to be typically incorporated by the hash computation. A hash funnel defines how an object is mapped to a byte sequence which is then used to compute the hash value. This is done, by describing the order in which elements of an object are put into a HashSink which accepts various standard types and primitives, and which finally takes care of the final mapping to a byte sequence.

Some special care is needed for object fields having variable size. If, for example, an object contains 2 string fields, both of which have varying lengths, it is not sufficient to put only their character sequences into the HashSink. Otherwise, the hash code contribution of the strings "ab" and "cde" would be the same as for "abc" followed by "de". In order to decrease the risk of hash collisions, it is also necessary to consider the lengths of the strings. This can be done by also providing the length of each string. When feeding the hash sink with the characters followed by the corresponding string lengths instead, the hash code contribution will be different as the two example would yield ["ab",2,"cde",3] and ["abc",3,"de",2], respectively.

It is better to append than to prepend the length information of types of variable size, because some data structures like Iterable require a pass over the data to determine its size. Therefore, it is better to first put the elements into the HashFunnel, followed by the length of the sequence.

  • Method Details

    • put

      void put(T obj, HashSink sink)
      Puts the object's content to the given HashSink.
      Parameters:
      obj - an object
      sink - a HashSink
    • forString

      static HashFunnel<String> forString()
      Returns a HashFunnel instance for String objects.
      Returns:
      a funnel
    • forEntry

      static <K, V> HashFunnel<Map.Entry<K,V>> forEntry(HashFunnel<K> keyHashFunnel, HashFunnel<V> valueHashFunnel)
      Returns a HashFunnel instance for Map.Entry objects.
      Type Parameters:
      K - key type
      V - value type
      Parameters:
      keyHashFunnel - funnel for keys
      valueHashFunnel - funnel for values
      Returns:
      a funnel for the entry