漫話:如何給女朋友解釋什么是XSWL?

導(dǎo)讀:什么是語(yǔ)法糖?

















switch自身原本就支持基本類型。比如int、char等。對(duì)于int類型,直接進(jìn)行數(shù)值的比較。對(duì)于char類型則是比較其ascii碼。switch中其實(shí)只能使用整型,任何類型的比較都要轉(zhuǎn)換成整型。比如byte,short,char(ackii碼是整型)以及int。switch對(duì)String得支持,有以下代碼:public?class?switchDemoString?{
????public?static?void?main(String[]?args)?{
????????String?str?=?"world";
????????switch?(str)?{
????????case?"hello":
????????????System.out.println("hello");
????????????break;
????????case?"world":
????????????System.out.println("world");
????????????break;
????????default:
????????????break;
????????}
????}
}
public?class?switchDemoString
{
????public?switchDemoString()
????{
????}
????public?static?void?main(String?args[])
????{
????????String?str?=?"world";
????????String?s;
????????switch((s?=?str).hashCode())
????????{
????????default:
????????????break;
????????case?99162322:
????????????if(s.equals("hello"))
????????????????System.out.println("hello");
????????????break;
????????case?113318802:
????????????if(s.equals("world"))
????????????????System.out.println("world");
????????????break;
????????}
????}
}
switch是通過(guò)equals()和hashCode()方法來(lái)實(shí)現(xiàn)的。




干貨直達(dá)??

評(píng)論
圖片
表情
