Uniform distribution of hashcode ()

I define my class as:

final class Key<T extends Comparable<T>> {
    private final T q;
    private final T o;
    public Key(T q1, T o1) {
        q = q1;
        o = o1;
    }

    @Override
    public boolean equals(Object obj) {
        if(obj != null && obj instanceof Key) {
            Key<T> s = (Key<T>)obj;
            return q.equals(s.q) && o.equals(s.o);
        }
        return false;
    }

    @Override
    public int hashCode() {
        return Objects.hash(q,o);
    }
}

I also define an array containing the key of the object. For instance:

Object arr[] = new Object[100];
Key<String> k = new Key<>("a","b");
int h = k.hashcode();
...
arr[h+i % h] = k; //i from 1 to 10 for example

The problem is that hashcode () can return a negative value, so

arr[h+i % h] = k;

may return an error from the array index. This is why I changed my code as (based on my search to avoid hashcode () to return a negative value):

@Override
        public int hashCode() {
            return (Objects.hash(q,o)&0x7FFFFFFF);
        }

So, if I do this, will the even distribution of the hash code () change or not? I mean that the probability of having the same value from two different objects will be increased or not?

+4
source share
2 answers

Object.hash() -, . Objects.hash( "B", "B" ) Objects.hash( "A", "a" ) -. ( BTW , )

Objects.hashCode("a", "a") Objects.hashCode("z", "z") 4065 4865, , , .

, , , .

+2

, Murmurhash MurmurHash - ? , Google guava .

import com.google.common.hash.HashCode; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing;

hashcode,

/**
     * getMurmur128Hash.
     * 
     * @param content
     * @return HashCode
     */
    public static HashCode getMurmur128Hash(String content) {
        final HashFunction hf = Hashing.murmur3_128();
        final HashCode hc = hf.newHasher().putString(content, Charsets.UTF_8).hash();
        return hc;
    }
    /**
     * getAbsMurmur128HashAsLongVal.
     * 
     * @param content
     * @return Long Absolute value of Long for the HashCode.
     */
    public static Long getAbsMurmur128HashAsLongVal(String content) {
        return Math.abs(getMurmur128Hash(content).asLong());
    }
+2

All Articles