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;
        }
  • 相关阅读:
    python实现决策树
    ag 命令的帮助文档
    Linux rsync 命令学习
    常用数学符号读法及其含义
    Python 数据分析
    Django 创建项目笔记
    Python 实用技巧
    Python 必备好库
    Pytest 简明教程
    Python 打包中 setpy.py settuptools pbr 的了解
  • 原文地址:https://www.cnblogs.com/zyf-yxm/p/10170257.html
Copyright © 2011-2022 走看看