码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-12-24 19:01:25      阅读:903      评论:0      收藏:0      [点我收藏+]

标签:string类   bsp   答案   计算   ati   方法   最大值   unsigned   strong   

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

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;
    }

 

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

标签:string类   bsp   答案   计算   ati   方法   最大值   unsigned   strong   

原文地址:https://www.cnblogs.com/zyf-yxm/p/10170257.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!