zoukankan      html  css  js  c++  java
  • 【深入Java基础】 switch用String作参数

    这里写图片描述

    一般情况switch只能用int(或者Integer)做参数,但是jdk17及其之后可以用枚举、String、float以及double作参数。

    - 为什么float和double不能做参数?

    事实上switch case语句只能判断int类型的数据,在比它小的数据类型比如byte、short可以自动转换为int,而比它大的比如float和double无法自动转换为int,所以会报错。当然String也是不可以的。

    - 为什么在jdk17之后就可以呢?

    因为对于String、float和double做参数时,实际上是比较的他们的hashCode,hashCode是一个整数,这样就可以接收非int型的参数了。并没有对原有的switch作修改。

    类似于这样:

          String s = "12";
            switch (s.hashCode())
            {
                case 1569://"12"的hashCode为1569
                    System.out.println("yes");
            }

    那么这个hashCode是怎么得到的呢?

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

    它是由 h = 31 * h + val[i]来计算哈希地址。val为字符串对应的char数组。

    例如”12”.hashCode() = 31 * 49 + 50 = 1569

    >>>对下于hash,将在下一篇文章中学习讨论 >>>。

  • 相关阅读:
    bzoj 5092: [Lydsy1711月赛]分割序列
    bzoj1173: [Balkan2007]Point
    bzoj1536: [POI2005]Akc- Special Forces Manoeuvres
    bzoj2178: 圆的面积并
    bzoj1043 下落的圆盘
    bzoj2674 Attack
    bzoj1201: [HNOI2005]数三角形
    bzoj3135: [Baltic2013]pipesd
    bzoj1760 [Baltic2009]Triangulation
    bzoj3136
  • 原文地址:https://www.cnblogs.com/cnsec/p/13286745.html
Copyright © 2011-2022 走看看