zoukankan      html  css  js  c++  java
  • 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;
        }
  • 相关阅读:
    游记 Day10
    游记 Day9
    NOIP模拟测试10
    【贪心】P3942 将军令 && P2279 消防局的设立
    在没有上考场之前,菜鸡也有翻盘的机会
    【数据结构】 圆方树&&广义圆方树
    快速幂&&龟速乘&&快速乘
    游记 Day 4
    【容斥】[ZJOI2016] 小星星
    游记 Day3
  • 原文地址:https://www.cnblogs.com/zyf-yxm/p/10170257.html
Copyright © 2011-2022 走看看