首页 > 其他分享 >String hashcode()

String hashcode()

时间:2023-02-17 11:13:49浏览次数:28  
标签:String val int 31 hashcode 98 97

String hashcode()代码段

  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;
    }
    @Test
    public void test() {

        //【对应Unicode字符集编码值a97;b98;c99】
        String s = new String("abc"); 

        //验证方式1、公式h=31 * h + val[i];
        //h=31*0+97=97
        //h=31*(31*0+97)+98=31*97+98=3105
        //h=31*[31*(31*0+97)+98]=31*3105+99=96354

        System.out.println(96354 == s.hashCode());//true

        //验证方式2:hashCode()计算公式:s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
        //h=97*31^(3-1)+98*31(2-1)+99*31(1-1)=96354
    }

标签:String,val,int,31,hashcode,98,97
From: https://www.cnblogs.com/haveanicedayfh/p/17129396.html

相关文章

  • String
    String概念:String的底层是一个封装的char[]数组特点因为String的底层是char[]数组,所以String的长度不可变创建实例String通常有两种创建实例的方式Stringstr="a......
  • Java—String类
    一、toString()方法1.publicStringtoString():返回对象的字符串;2.toString(),返回的是对象的地址值,没有实际意义,需要重写;重写规制:返回对象的属性值;getClass.getNam......
  • String详解
    String对象的不可变原因,String对象的内存布局,及String对象之间的执行==,equals,+运算时的分析。Author:MsuenbDate:2023-02-16java.lang.String类代表字符串。String......
  • char* 和std::string的生命周期
    std::string跟普通的c++对象一样,在对应的local/global的域内自动释放(包括string指向的字符串)。因此{std::stringabc="abc";}"abc"在花括号外就被自动释放了。而ch......
  • [ABC272F] Two Strings 题解
    [ABC272F]TwoStringsSolution目录[ABC272F]TwoStringsSolution更好的阅读体验戳此进入题面SolutionCodeUPD更好的阅读体验戳此进入题面给定两字符串$S,T$,求......
  • APS.NET Core 6.0Json任何类型读取到字符串属性The JSON value could not be converte
    在升级.netsdk到6.0版本后出现TheJSONvaluecouldnotbeconvertedtoSystem.String.原因是我代码定义的类型是string,但是传参的时候写了int,publicoverridevoidC......
  • hex转string,hex转字符串,hex16进制转字符串,hex转中文
    hex转字符串,hex16进制转字符串,在线工具 https://www.toolscat.com/decode/hexhex转字符串,hex转string,string转hex,16进制转字符串,hex转字符串在线工具,hex转str在线......
  • String概述以及常用方法
    publicclassDemo01{publicstaticvoidmain(String[]args){Stringname="hello";//“hello”常量存储在字符串池中,字符串池在方法区中,字符串字面值可......
  • String案例演示
    publicclassApplication{publicstaticvoidmain(String[]args){Stringstr="thisisatext";//1将str中的单词单独获取出来Strin......
  • String.format()在android中的应用
    android中string.xml中%1$s、%1$d等的用法一,不使用xliff的用法:1、整型,比如“小姐今年23岁了”,这个23是整型的。在string.xml中可以这样写,Java代......