java7 語(yǔ)法糖 之 switch 語(yǔ)句中的string
來(lái)源:程序員人生 發(fā)布時(shí)間:2014-11-15 07:48:10 閱讀次數(shù):3333次
Jdk7新增的switch 語(yǔ)句中常量可以string類型,
例如:
@Test
public void test_1(){
String string = "hello";
switch (string) {
case "hello":
System.out.println(string);
break;
default:
throw new IllegalArgumentException("非法參數(shù)");
}
}
語(yǔ)法糖的背后,其實(shí)用的對(duì)待string 類型時(shí)候,用的是hashCode() 方法轉(zhuǎn)換的.
所以string 類型不能為 NULL.
例如:
@Test
public void test_3(){
String string = null;
expectedException.expect(NullPointerException.class);
switch (string) {
case "hello":
System.out.println(string);
break;
default:
throw new IllegalArgumentException("非法參數(shù)");
}
}
會(huì)拋出異常
NullPointerException
生活不易,碼農(nóng)辛苦
如果您覺(jué)得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)