Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a hash from several Java string objects

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);
}
like image 337
PNS Avatar asked May 14 '12 16:05

PNS


People also ask

How to get the hash code of a string in Java?

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.

How does the hash() method work in JavaScript?

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:

How to loop through the items of an HashSet in Java?

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.

What is the use of hashing in Java?

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.


2 Answers

Here is the simple implementation using Objects class available from Java 7.

@Override
public int hashCode()
{
    return Objects.hash(this.variable1, this.variable2);
}
like image 124
girivasan4 Avatar answered Oct 12 '22 11:10

girivasan4


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...).

like image 23
Oliver Coleman Avatar answered Oct 12 '22 12:10

Oliver Coleman