Java中的switch

來源:互聯網
上載者:User

標籤:就是   static   hash衝突   ash   short   可見   mod   ati   運算式   

 switch語句的作用其實就相當於if()else,就是一種選擇語句,文法如下:

switch(運算式){     case 常量運算式1:  語句1;    case 常量運算式2:  語句2;    …     case 常量運算式n:  語句n;    default:  語句n+1;}

需要注意的是switch中運算式的類型可以是byte,short,char,int,enum類型,java7之後

可以使string類型也支援作為運算式,可以研究下原理:

public class StringInSwitchCase {       public static void main(String[] args) {             String mode = args[0];             switch (mode) {                   case "ACTIVE":                         System.out.println("Application is running on Active mode");                         break;                   case "PASSIVE":                        System.out.println("Application is running on Passive mode");                          break;                   case "SAFE":                           System.out.println("Application is running on Safe mode");           }       } }

將上述代碼進行反編譯:

public class StringInSwitchCase{       public StringInSwitchCase() { }       public static void main(string args[]) {              String mode = args[0];             String s; switch ((s = mode).hashCode()) {                   default: break;                   case -74056953:                         if (s.equals("PASSIVE")) {                                     System.out.println("Application is running on Passive mode");                          }                         break;                   case 2537357:                         if (s.equals("SAFE")) {                               System.out.println("Application is running on Safe mode");                          }                         break;                   case 1925346054:                         if (s.equals("ACTIVE")) {                               System.out.println("Application is running on Active mode");                          }                         break;                }           } }

可以清晰的看到,java底層是對string調用了hashCode()方法,而返回的hashCode是int類型,其實還是用hashCode

進行case,然後再用equals進行比較,滿足條件後便執行相應的語句。

由此可見使用string作為運算式不如直接使用整形或者枚舉效率高,因為使用string會額外調用hashCode方法,而且換有可能

出現hash衝突。其實我們在編程中更多地還是使用枚舉來進行條件判斷。

Java中的switch

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.