What happens if hashcode calculated exceeds the INTEGER MAX LIMIT?

烈酒焚心 提交于 2019-12-07 12:20:55

问题


Here is the hashCode() implementation from Java HashTable Class. What if the number of elements in the hashtable is huge and the hashcode exceeds the INTEGER MAX LIMIT -2,147,483,648 to 2,147,483,647 ? I assume hashCodes will be positive integers.

 public synchronized int hashCode() {

    int h = 0;
    if (count == 0 || loadFactor < 0)
        return h;  // Returns zero

    loadFactor = -loadFactor;  // Mark hashCode computation in progress
    Entry[] tab = table;
    for (int i = 0; i < tab.length; i++)
        for (Entry e = tab[i]; e != null; e = e.next)
            h += e.key.hashCode() ^ e.value.hashCode();
    loadFactor = -loadFactor;  // Mark hashCode computation complete

    return h;
}

回答1:


I assume hashCodes will be positive integers.

No, not necessarily. They're just integers. They can definitely be negative, and it's fine to have integer overflow while computing a hash code. An ideal hash code will be spread uniformly across the whole of its range (int in this case). Anything using a hash code definitely needs to take into account the possibility of the value being negative.




回答2:


Sometimes getting an overflow on the integer may be unsuitable to your needs. I say this as sometimes. I still have yet to encounter this situation but I would like to prevent it.

I'll paste you the code I use to generate a hashcode. I usually do it by taking all vars from an object and convert them to strings and do my calculations.

public static int generateHashCode(String ... args)
{
    int length = 0;
    char[] cArray = null;
    if(args.length == 1) {
        length = args[0].length();
        cArray = args[0].toCharArray();
    }
    else {
        for(int i = 0; i < args.length; i++) {
            length += args[i].length();
        }

        cArray = new char[length];
        int incrementer = 0;
        for(int i = 0; i < args.length; i++) {
            String str = args[i];
            for(int j = 0; j < str.length(); j++) {
                cArray[incrementer] = str.charAt(j);
                ++incrementer;
            }
        }
    }

    int h = 0;
    for (int i = 0; i < cArray.length; i++) {
        h = 31*h + cArray[i];
    }

    return h;
}


来源:https://stackoverflow.com/questions/11113871/what-happens-if-hashcode-calculated-exceeds-the-integer-max-limit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!