Use string in switch case in java

前端 未结 13 1662
盖世英雄少女心
盖世英雄少女心 2020-12-01 07:30

I need to change the following if\'s to a switch-case while checking for a String, to improve the cyclomatic complexity.<

相关标签:
13条回答
  • 2020-12-01 07:35

    Learn to use else.

    Since value will never be equal to two unequal strings at once, there are only 5 possible outcomes -- one for each value you care about, plus one for "none of the above". But because your code doesn't eliminate the tests that can't pass, it has 16 "possible" paths (2 ^ the number of tests), of which most will never be followed.

    With else, the only paths that exist are the 5 that can actually happen.

    String value = some methodx;
    if ("apple".equals(value )) {
        method1;
    }
    else if ("carrot".equals(value )) {
        method2;
    }
    else if ("mango".equals(value )) {
        method3;
    }
    else if ("orance".equals(value )) {
        method4;
    }
    

    Or start using JDK 7, which includes the ability to use strings in a switch statement. Course, Java will just compile the switch into an if/else like construct anyway...

    0 讨论(0)
  • 2020-12-01 07:38

    Everybody is using at least Java 7 now, right? Here is the answer to the original problem:

    String myString = getFruitString();
    
    switch (myString) {
    
        case "apple":
            method1();
            break;
    
        case "carrot":
            method2();
            break;
    
        case "mango":
            method3();
            break;
    
        case "orange":
            method4();
            break;
    }
    

    Notes

    • The case statements are equivalent to using String.equals.
    • As usual, String matching is case sensitive.
    • According to the docs, this is generally faster than using chained if-else statements (as in cHao's answer).
    0 讨论(0)
  • 2020-12-01 07:39

    Java (before version 7) does not support String in switch/case. But you can achieve the desired result by using an enum.

    private enum Fruit {
        apple, carrot, mango, orange;
    }
    
    String value; // assume input
    Fruit fruit = Fruit.valueOf(value); // surround with try/catch
    
    switch(fruit) {
        case apple:
            method1;
            break;
        case carrot:
            method2;
            break;
        // etc...
    }
    
    0 讨论(0)
  • 2020-12-01 07:39
    String value = someMethod();
    switch(0) {
    default:
        if ("apple".equals(value)) {
            method1();
            break;
        }
        if ("carrot".equals(value)) {
            method2();
            break;
        }
        if ("mango".equals(value)) {
            method3();
            break;
        }
        if ("orance".equals(value)) {
            method4();
            break;
        }
    }
    
    0 讨论(0)
  • 2020-12-01 07:41

    Not very pretty but here is another way:

    String runFct = 
            queryType.equals("eq") ? "method1":
            queryType.equals("L_L")? "method2":
            queryType.equals("L_R")? "method3":
            queryType.equals("L_LR")? "method4":
                "method5";
    Method m = this.getClass().getMethod(runFct);
    m.invoke(this);
    
    0 讨论(0)
  • 2020-12-01 07:42

    Just to make concrete emory's answer, the executable code is the following :

      Map<String,Callable<USer>> map = new HashMap<String,Callable<User>>();
      map.put( "test" , new Callable<User> () { public User call (){ return fillUser("test" ); }} ) ;
      map.put( "admin" , new Callable<Utente> () { public Utente call (){  return fillUser("admin" ); }} ) ;
    

    where user is a POJO, and then

      User user = map.get(USERNAME).call();
    

    finally the called method is somewhere :

     private User fillUser(String x){        
            User user = new User();
            // set something in User
            return user;
    }
    
    0 讨论(0)
提交回复
热议问题