Use string in switch case in java

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

    Here is a possible pre-1.7 way, which I can't recommend:

    public class PoorSwitch
    {
        final static public int poorHash (String s) {
            long l = 0L;
            for (char c: s.toCharArray ()) {
                l = 97*l + c;
            }
            return (int) l;
        }
    
        public static void main (String args[])
        {
            String param = "foo";
            if (args.length == 1)
            {
                param = args[0];
            }
            // uncomment these lines, to evaluate your hash
            // test ("foo");
            // test ("bar");
            switch (poorHash (param)) {
                // this doesn't work, since you need a literal constant
                // so we have to evaluate our hash beforehand:
                // case poorHash ("foo"): {
                case 970596: {
                    System.out.println ("Foo!");
                    break;
                }
                // case poorHash ("bar"): {
                case 931605: {
                    System.out.println ("Bar!");
                    break;
                }
                default: {
                    System.out.println ("unknown\t" + param);
                    break;
                }
            }
        }
    
        public static void test (String s)
        {
            System.out.println ("Hash:\t " + s + " =\t" + poorHash (s));
        }
    }
    

    Maybe you could work with such a trick in a generated code. Else I can't recommend it. Not so much that the possibility of a hash collision makes me worry, but if something is mixed up (cut and paste), it is hard to find the error. 931605 is not a good documentation.

    Take it just as proof of concept, as curiosity.

提交回复
热议问题