Switch cases maximum implementation?

前端 未结 7 1750
没有蜡笔的小新
没有蜡笔的小新 2021-01-19 12:27

I am using a single switch cases which will have more than 100 cases statement to be used. Are there any limit ?

The usage of cases are for the suggestions of my Aut

7条回答
  •  北荒
    北荒 (楼主)
    2021-01-19 12:55

    There is a limit imposed on the maximum method length: Maximum size of a method in java?

    Otherwise, as an example, a switch with 1000 cases of the form

    casen: System.out.println(n); break;

    seems to work. The generated bytecode uses a tableswitch instruction, which means it shouldn't even be inefficient.

    Of course, unless it's automatically generated code, this will be frowned upon.

    Think of alternatives, such as:

    • a map/array of values (if your cases just return or produce a value of some kind);
    • a map/array of objects that will run the necessary code (depending on the exact conditions, you might end up with less code this way).

    Edit:

    Looking at your code, it seems, since all your case statements run the exact same type of code, all you need is a Class[] accessed by index, something like:

    Class[] myArray = new Class[...];
    myArray[0] = Adidas.class;
    //...
    
    //instead of the switch
    startActivity(new Intent(Search.this, myArray[index])); 
    

    And of course, it would be prettier if there were a way to produce those classes some other way, say if you had Adidas and Affin objects, and you ran getClass() on them, or if you had a list of their names and could use Class.forName.

提交回复
热议问题