栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java基础-篇章2

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java基础-篇章2

switch语句的用法 用法一:
public class Main {
    public static void main(String[] args) {
        String fruit = "apple";
        switch (fruit) {
        case "apple":
            System.out.println("Selected apple");
            break;
        case "pear":
            System.out.println("Selected pear");
            break;
        case "mango":
            System.out.println("Selected mango");
            break;
        default:
            System.out.println("No fruit selected");
            break;
        }
    }
}

注意点:要记得写break(case语句具有穿透效应,如果不写的话,后面的会继续执行);要记得写default(都不匹配的情况);

简洁的用法:
public class Main{
    public static void main(String[] args){
        String fruit="ban";
        switch (fruit){
            case "apple"->System.out.println("select a");
            case "banana"->System.out.println("select b");
            case "mango"->System.out.println("select mango");
            default ->System.out.println("select none");
        }
        // System.out.println("哈哈哈");
    }
}

直接使用箭头来表示switch的返回值,没有了写很多break的繁琐

这种简介的写法还可以直接返回值:

public class Main {
    public static void main(String[] args) {
        String fruit = "a";
        int option = switch (fruit) {
            case "a" -> 1;
            case "p", "m" -> 2;
            default -> 0;
        }; // 注意使用赋值语句要以;结束
        System.out.println("opt = " + option);
    }
}
使用yield来返回值:
public class Main {
    public static void main(String[] args) {
        String fruit = "orange";
        int opt = switch (fruit) {
            case "apple" -> 1;
            case "pear", "mango" -> 2;
            default -> {
                int code = fruit.hashCode();
                yield code;
            }
        };
        String c="a";
        System.out.println(c.hashCode());
        System.out.println("opt = " + opt);
    }
}

说明:其中使用了String的hashcode方法,这个方法是以31为权,每一位为字符的ASCII值进行运算,用自然溢出来等效取模,得到一个不容易重复的数字,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;
}

然后还使用了yield来返回值,注意只有switch使用->的简洁写法才可以使用yield返回值。

参考资料:

Java编程:String 类中 hashCode() 方法详解_志波同学的博客-CSDN博客_string.hashcode()

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/974311.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号