hashCode会出现负数吗,答案是肯定的

先来普及一下基本数据类型的长度:

unsigned   int   0~4294967295   
int   -2147483648~2147483647 
unsigned long 0~4294967295
long   -2147483648~2147483647
long long的最大值:9223372036854775807
long long的最小值:-9223372036854775808
unsigned long long的最大值:1844674407370955161

__int64的最大值:9223372036854775807
__int64的最小值:-9223372036854775808
unsigned __int64的最大值:18446744073709551615

 

String类的hashCode方法是通过int来修饰的,只要hashcode的计算结果超出了int的范围就会产生溢出

 

//这是String类的方法
private
final char value[]; private int hash; public int hashCode() { int h = hash; if (h == 0 && value.length > 0) { char val[] = value; for (int i = 0; i < value.length; i++) { h = 31 * h + val[i]; } hash = h; } return h; }

//注:"420112199111183939".hashCode(); -->结果是:-61

 

如果要防止hashcode结果溢出,可以重写hashcode的方法

private static long myHashCode(String str) {
        long h = 0;
        if (h == 0) {
            int off = 0;
            char val[] = str.toCharArray();
            long len = str.length();
 
            for (long i = 0; i < len; i++) {
                h = 31 * h + val[off++];
            }
        }
        return h;
    }

 

转载于:https://www.cnblogs.com/zyf-yxm/p/10170257.html

你可能感兴趣的:(hashCode会出现负数吗,答案是肯定的)