What would be the fastest and more robust (in terms of uniqueness) way for implementing a method like
public abstract String hash(String[] values);
The values[]
array has 100 to 1,000 members, each of a which with few dozen characters, and the method needs to be run about 10,000 times/sec on a different values[]
array each time.
Should a long string be build using a StringBuilder
buffer and then a hash method invoked on the buffer contents, or is it better to keep invoking the hash method for each string from values[]
?
Obviously a hash of at least 64 bits is needed (e.g., MD5) to avoid collisions, but is there anything simpler and faster that could be done, at the same quality?
For example, what about
public String hash(String[] values)
{
long result = 0;
for (String v:values)
{
result += v.hashCode();
}
return String.valueOf(result);
}
The hashCode () method returns the hash code of a string. where s [i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. None.
Under the hood, the hash () method works by putting the supplied objects into an array and calling Arrays.hashCode () on them. If we provide only one object to the Objects.hash () method, we can't expect the same results as calling Objects.hashCode () on the object. First, let's call Objects.hash () with two pairs of identical strings:
Loop through the items of an HashSet with a for-each loop: Items in an HashSet are actually objects. In the examples above, we created items (objects) of type "String". Remember that a String in Java is an object (not a primitive type). To use other types, such as int, you must specify an equivalent wrapper class: Integer.
Hashing in Java. In hashing there is a hash function that maps keys to some values. But these hashing function may lead to collision that is two or more keys are mapped to same value.
Here is the simple implementation using Objects class available from Java 7.
@Override
public int hashCode()
{
return Objects.hash(this.variable1, this.variable2);
}
It doesn't provide a 64 bit hash, but given the title of the question it's probably worth mentioning that since Java 1.7 there is java.util.Objects#hash(Object...).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With