关于jdk7中的新语法带String的switch

来源:互联网 发布:linux文件权限777 编辑:程序博客网 时间:2024/04/28 02:13

 在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语句中.

原创粉丝点击