java7 switch语句中使用字符串的背后原理

先看下代码及反编译后的代码:

/**
 * @author doctor
 *
 * @time 2015年3月28日 下午3:26:06
 */
public class StringForSwitch {
	
	@Rule
	public ExpectedException ex = ExpectedException.none();

	@Test
	public void test_string_switch() {
		String result="";
		
		switch ("doctor") {
		case "doctor":
			result = "doctor";
			break;
		
		default:
			break;
		}
		
		assertThat(result, equalTo("doctor"));
	}

	
	 
}

反编译后的代码:

public class StringForSwitch {
    @Rule
    public ExpectedException ex = ExpectedException.none();

    public StringForSwitch() {
    }

    @Test
    public void test_string_switch() {
        String result = "";
        String var2 = "doctor";
        switch("doctor".hashCode()) {
        case -1326477025:
            if(var2.equals("doctor")) {
                result = "doctor";
            }
        default:
            Assert.assertThat(result, IsEqual.equalTo("doctor"));
        }
    }
}

1.字符串类型在switch语句中利用hashcode的值与字符串内容的比较来实现的.

2.因为字符串的哈希值可能重复,哈希函数设计的不好吧.故还得需要进一步比较字符串的内容.

3.编译器层面的语法糖而已,实质没变,switch还是比较的整数.

4.jdk1.8.0_40环境下.

转载于:https://my.oschina.net/doctor2014/blog/393057

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值