Reputation: 11
I am looking for a hash function for an integer array containing about 17 integers each. There are about 1000 items in the HashMap and I want the computation to be as fast as possible.
I am now kind of confused by so many hash functions to choose and I notice that most of them are designed for strings with different characters. So is there a hash function designed for strings with only numbers and quick to run?
Thanks for your patience!
Upvotes: 1
Views: 1989
Reputation: 262464
You did not specify any requirements (except speed of calculation), but take a look at java.util.Arrays#hashCode. It should be fast, too, just iterating once over the array and combining the elements in an int
calculation.
Returns a hash code based on the contents of the specified array. For any two non-null int arrays a and b such that Arrays.equals(a, b), it is also the case that Arrays.hashCode(a) == Arrays.hashCode(b).
The value returned by this method is the same value that would be obtained by invoking the hashCode method on a List containing a sequence of Integer instances representing the elements of a in the same order. If a is null, this method returns 0.
And the hashmap accepts an array of integer as the key.
Actually, no!
You could technically use int[]
as a key in a HashMap
in Java (you can use any kind of Object
), but that won't work well, as arrays don't define a useful hashCode
method (or a useful equals
method). So the key will use object identity. Two arrays with identical content will be considered to be different from each-other.
You could use List<Integer>
, which does implement hashCode
and equals
. But keep in mind that you must not mutate the list after setting it as a key. That would break the hashtable.
Upvotes: 1
Reputation: 505
hashmap functions can be found in https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
Creating a hashmap is easy.. it goes as
HashMap<Object, Integer> map = new HashMap<Object, Integer>();
Upvotes: 0