Switch cases maximum implementation?

前端 未结 7 1661
没有蜡笔的小新
没有蜡笔的小新 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

    The code will become unmanageable before you hit any limit that Java imposes.

    Have you considered refactoring the code? Depending on what the switch statement is designed to achieve you could either:

    • Use a map to provide different results
    • Create a hierarchy of simple objects that give the behaviour you require for each case

    So in your case, you would be better off defining a static Map of index values to Classes:

    public class MyClass
    {
        private static final Map LOOKUP = 
          new HashMap(...);
        static
        {
          LOOKUP.put(0, Adidas.class);
          LOOKUP.put(1, Affin.class);
          ...
        }
    
        public void onItemClick(...)
        {
          ...
          // Replace switch statement with:
          if (LOOKUP.containsKey(index))
          {
            startActivity(new Intent(Search.this, LOOKUP.get(index)));
          }
          else
          { 
            Toast.makeText(Search.this, 
                           "Invalid Selection", 
                           Toast.LENGTH_SHORT).show();
          }
        }
        ...
      }
    

    This makes the code in onItemClick() easier to read. You could go one step further and define a private startActivity() method that takes the index to be used and contains all the switch statement replacement code.

提交回复
热议问题