Java中switch处理字符串的原理

引言

switch对字符串的支持是从JDK7开始的

实现原理

switch对字符串的处理和基本数据类型的处理有一点点的不一样,
它会字符串转为HashCode码来转到对应的分支,分支中的字符串也会转成HashCode码,HashCode码为int类型,switch这样处理字符串就和int类型的一致,只是在内部再一次使用equals对原字符串进行比较

代码示例

public class SwitchStringDemo {

    public static void main(String[] args) {

        // String
        String str = "two";
        switch (str) {
            case "one":
                System.out.println("one");
                break;
            case "two":
                System.out.println("two");
                break;
            default:
                System.out.println("其他...");
                break;
        }
        
        // int
        int num = 1;
        switch (num) {
            case 1:
                System.out.println("1111111");
                break;
            case 2:
                System.out.println("2222222");
                break;
            default:
                System.out.println("其他...");
                break;
        }
    }

}

反编译代码

public class SwitchStringDemo {
	public static void main(String[] args) {
		// String类型的switch
		label25 : {
			String str = "two";
			switch (str.hashCode()) {   // 此处使用字符串的HashCode码
				case 110182 :   // 字符串转为HashCode码
					if (str.equals("one")) {  // 再一次使用equals比较
						System.out.println("one");
						break label25;
					}
					break;
				case 115276 :   // 字符串转为HashCode码
					if (str.equals("two")) {
						System.out.println("two");
						break label25;
					}
			}

			System.out.println("其他...");
		}

        // int类型的switch
		int num = 1;
		switch (num) {
			case 1 :
				System.out.println("1111111");
				break;
			case 2 :
				System.out.println("2222222");
				break;
			default :
				System.out.println("其他...");
		}

	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值