首页 > 其他分享 >String的hashCode可能会返回负数&解决方案

String的hashCode可能会返回负数&解决方案

时间:2022-12-01 22:56:11浏览次数:35  
标签:String int 解决方案 value 负数 abs hashCode

String的hashCode可能会返回负数&解决方案

产生原因:

  • 可以查看String hashCode()的源码,会发现,它使用的是int类型,这个时候如果字符串过长,则会溢出
    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;
    }

解决方案:

  • 不能直接使用abs,abs也可能溢出,例如System.out.println(Math.abs(Integer.MIN_VALUE));输出的是-2147483648
  • 可以使用str.hashCode()&Integer.MAX_VALUE;来保证为正数

标签:String,int,解决方案,value,负数,abs,hashCode
From: https://www.cnblogs.com/lavender-pansy/p/16943060.html

相关文章

  • string.Join用法
    原文链接:https://blog.csdn.net/useringo/article/details/51684370String.Join方法(String,String[])在指定String数组的每个元素之间串联指定的分隔符String,从而......
  • 43. Multiply Strings(重要)
    Giventwonumbersrepresentedasstrings,returnmultiplicationofthenumbersasastring.Note:Thenumberscanbearbitrarilylargeandarenon-negative.Conv......
  • 3. Longest Substring Without Repeating Characters(难,重要)
    longestsubstringExamples:​​"abcabcbb"​​,theansweris ​​"abc"​​,whichthelengthis3.​​"bbbbb"​​,theansweris ​​"b"​​,withthelengtho......
  • 一文了解 Go 标准库 strconv:string 与其他基本数据类型的转换
    耐心和持久胜过激烈和狂热。哈喽大家好,我是陈明勇,今天分享的知识是Go标准库——strconv。如果本文对你有帮助,不妨点个赞,如果你是Go语言初学者,不妨点个关注,一起成长一......
  • NSMutableAttributedString
    1、Key值介绍1.1详细介绍NSFontAttributeName字体:该属性所对应的值是一个UIFont对象。该属性用于改变一段文本的字体。如果不指定该属性,则默认为12-pointHelvet......
  • CS144 lab1: stitching substrings into a byte stream
    CS144lab1:stitchingsubstringsintoabytestream​ Lab1中我们主要实现一个叫做StreamReassembler的东西。从Lab1提供的文档中,我们可以大致了解未来我们将要自己实......
  • C++ wchar_t char wstring string 转换
    1.wchart_t转wstring1wchar_ttmpRuleStr[10]={0};2wstringm_tmpRuleStr=wstring(tmpRuleStr);2.wstring转wchar_t1wstringstr="123";2wchar_t*tmp=......
  • String.join() 字符串拼接
    例1:classProgram{staticvoidMain(string[]args){List<string>list=newList<string>();list.Add("a");list.Add("b"......
  • Decrypt string in C# that was encrypted with PHP openssl_encrypt
    DecryptstringinC#thatwasencryptedwithPHPopenssl_encrypt回答1WellthiswasfuntoworkoutandrequiredjumpingintothePHPsourcecodewithsome......
  • 字符串(StringUtils)
    字符串(StringUtils)介绍遵从两大原则1.绝不依赖JDK以外的源码2.牺牲代码复用性,每个类都必须是单独的组件,绝不互相引用,做到完全解耦package*;importcom.sun.......