解决switch……case不能匹配字符串的方法

以前写代码的时候,没有考虑到效率的问题。if……else if……else if 写了老长。如果数据量特别大的话,其实会影响到程序的效率。因为,if语句是从上到下一个个判断的,直到条件为真才退出。而switch……case 则不是从上到下进行验证的,因此效率要比if else高。

 

可惜的是,switch case 不支持字符串,着实让我伤脑筋。今天在网上查了些资料,得到一些提示,拿出来晒晒。

 

if……else例子:

 

 public void  ifElse(){


       String name="haha";
       if(name.equals("yes")){
        System.out.println("is yes");
       }
       else if(name.equals("hello")){
        System.out.println("is hello");
       }
       else if(name.equals("in")){
        System.out.println("is in");
       }
       else if(name.equals("haha")){
        System.out.println("is haha");
       }
 }

 

代码难看,如果if 再长一点,就难受了。

 

用switch case 实现:

 

 public void switchCaseStr() {
  
  Map<String,Integer> map=new HashMap<String, Integer>();
  
  map.put("hello", 1);
  map.put("haha", 2);
  map.put("yes", 3);
  map.put("in", 4);
  
 
  String str="hello";
  
  switch(map.get(str))
  {    
   case 3:
        System.out.println("yes");
       break;
   case 1:
        System.out.println("hello");
        break;
    case 2:
        System.out.println("haha");
       break;
    case 4:
       System.out.println("in");
       break;
  
   default:
    System.out.println("default");
  }
 }

 

     不仅从效率上有提高,而且代码也更好看。当然,switch case 还可以嵌套使用。

 

   public void switchCaseStr(){

 

  Map<String,Integer> map=new HashMap<String, Integer>();
  
  map.put("hello", 1);
  map.put("haha", 2);
  map.put("yes", 3);
  map.put("in", 4);
  
 
  String str="hello";
  
  switch(map.get(str))
  {    
   case 3:
    System.out.println("yes");
    break;
   case 1:
    System.out.println("hello");
    
    String st="in";
    switch(map.get(st))
    {
    case 2:
     System.out.println("haha");
     break;
    case 4:
     System.out.println("in");
     break;
    }
    break;
   default:
    System.out.println("default");
  }

 

 

}

 

     当然,也可以有其它的方法实现。本人喜欢用hashmap,效率应该比 List好一点吧,个人觉得。

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值