Use string in switch case in java

前端 未结 13 1757
盖世英雄少女心
盖世英雄少女心 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: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).

提交回复
热议问题