views:

489

answers:

2

How can I generate hash value for a byte array, in J2ME?

It doesn't have to be very very secure but it should be fast.

A: 

If you already have a dependency on Apache Commons Lang you may as well use HashCodeBuilder:

new HashCodeBuilder().append(bytes).toHashCode();
Hilton Campbell
+2  A: 

As suggested by Josh Bloch in his Effective Java book:

public int hashCode() {
   int result = 17;
   for (int i = 0; i < array.length; i++) {
      result = 31*result + (int)array[i];
   }
   return result;
}
Boris Pavlović
do you by any chance remember the reasoning why to use 31? It is a prime number, but there was some other reason too that I dont remember.
martinus
i think that bloch wrote that for some reasons backed up by mathematical theories prime number is used. it allows uniform distribution of keys in the hash table preventing creation of linked lists of values whose keys have the same hash code
Boris Pavlović
Jader Dias