Search code examples
javastringsignature

Is there a way to quickly compute the signature of a string for help detecting string changes?


We have a non-critical tag whose value is a string. We want to check the changes of the tag value. But we don't want to do string comparison as this involves client-server and instead we want to calculate some sort of value for the string and use the value to help detect the string changes. As the string is non-critical, we wonder if there is a very simple and quick solution to calculate such value for helping on detecting changes to the string.


Solution

  • Use the .hashCode()

    String.hashCode() isn't perfect because it is lossy. So it's possible the string could change and it would have the same hashcode. (but this won't happen often) Almost every time the string changes, its hash code will change also.

    So you know what you're getting into, the code for String.hashCode() is this:

    public int hashCode() {
        int h = hash;  // the cached hash value
        int len = count;  // the number of characters in the string
        if (h == 0 && len > 0) {
            int off = offset;
            char val[] = value;
    
            for (int i = 0; i < len; i++) {
                h = 31*h + val[off++];
            }
            hash = h;
        }
        return h;
    }