關於jdk7中的新文法帶String的switch

來源:互聯網
上載者:User

 在jdk7之前的switch只能使用byte short int char enum.一旦使用了

  String value = "Hello";
  switch(value){
   case "Hello" :
     System.out.println("Hello");
   break;
   case "hh" :
     System.out.println("hh");
     break;
   case "h" :
     System.out.println("h");
     break;
   default :
     System.out.println("default");
  }

就會有

HelloWorld.java:12: 不相容的類型
找到: java.lang.String
需要: int
                switch(value){

 

在jdk7中,你完全可以大膽的使用.對應的java編譯成class其實是

String value = "Hello";
    String str = value;
 int i = -1;
 switch (str.hashCode())
    {
    case "Hello".hashCode():
      if (str.equals("Hello")) i = 0; break;
    case "hh".hashCode() :
      if (str.equals("hh")) i = 1; break;
    case "h".hashCode() :
      if (str.equals("h")) i = 2; 
 }
 
    switch (i)
    {
    case 0:
      System.out.println("Hello");
      break;
    case 1:
      System.out.println("hh");
      break;
    case 2:
      System.out.println("h");
      break;
    default:
      System.out.println("default");
    }
由上面的例子我們可以看出是產生了兩個swtich語句,把String 轉成對應的hashCode值放入

第一個switch語句中.定義了一個變數i,值從-1開始.把結果放到第二個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.