切换案例最大化实施?

时间:2012-01-27 09:56:40

标签: java programming-languages switch-statement

我正在使用单个交换机案例,它将使用超过100个案例语句。有没有限制?

案例的使用是针对我的AutoCompleteTextView,android教程的建议。

以下是我的代码的一部分,忽略了Badrul.class,稍后会更改它们。

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Toast;

public class Search extends Activity
{
    public void onCreate(Bundle savedInstanceSate)
    {
        final AutoCompleteTextView autoComplete;
        super.onCreate(savedInstanceSate);
        setContentView(R.layout.searchshop);

        autoComplete = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, shops);
        autoComplete.setAdapter(adapter); 
        autoComplete.setThreshold(1);
        autoComplete.setOnItemClickListener(new OnItemClickListener()
        {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) 
        {
            int index=999;
            for(int i=0;i<shops.length;i++)
            {
                if(autoComplete.getText().toString().trim().equals(shops[i]))
                {
                    index=i;
                    break;
                }
            }

                switch(index)
                {
                case 0:
                    startActivity(new Intent(Search.this, Adidas.class));
                    break;

                case 1:
                    startActivity(new Intent(Search.this, Affin.class));
                    break;
                case 2:
                    startActivity(new Intent(Search.this, AlamArt.class));
                    break;
                case 3:
                    startActivity(new Intent(Search.this, AlAmin.class));
                    break;
                case 4:
                    startActivity(new Intent(Search.this, Anakku.class));
                    break;
                case 5:
                    startActivity(new Intent(Search.this, Anggerik.class));
                    break;
                case 6:
                    startActivity(new Intent(Search.this, Asiari.class));
                    break;
                case 7:
                    startActivity(new Intent(Search.this, AsterSpring.class));
                    break;
                case 8:
                    startActivity(new Intent(Search.this, Audrey.class));
                    break;
                case 9:
                    startActivity(new Intent(Search.this, Badrul.class));
                    break;
                case 10:
                    startActivity(new Intent(Search.this, Badrul.class));
                    break;
                case 11:
                    startActivity(new Intent(Search.this, Badrul.class));
                    break;
                default:
                    Toast.makeText(Search.this, "Invalid Selection", Toast.LENGTH_SHORT).show();
                }
            }
            });

        }
static final String[] shops = new String[]
            {
                "Adidas", "Affin Bank ATM", "Alam Art Gallery", "Al Amin Kids", "Anakku", "Anggerik", "Asiari", 
                "Aster Spring", "Audrey", "Badrul Songket", "Bata"};
}

7 个答案:

答案 0 :(得分:7)

在达到Java强加的任何限制之前,代码将变得难以管理。

您是否考虑过重构代码?根据switch语句的设计目标,您可以:

因此,在您的情况下,最好将Map的索引值定义为Classes

public class MyClass
{
    private static final Map<Integer, Class> LOOKUP = 
      new HashMap<Integer, Class>(...);
    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();
      }
    }
    ...
  }

这使得onItemClick()中的代码更易于阅读。您可以更进一步,定义一个私有startActivity()方法,该方法使用索引并包含所有switch语句替换代码。

答案 1 :(得分:4)

Switch可以正常使用byte,short,char和int。所以你有int值+ default的限制。来自here

但我建议更多地考虑建筑。最好组织一些接口'执行者'并实现一些执行者(可以作为内部类)。然后你只需要一个数组(map),你将拥有这些表演者的条件和实例。我们的想法是将数据与算法分开。

此外,您可能会尝试找到其他模式

答案 2 :(得分:3)

最大方法长度有限制:Maximum size of a method in java?

否则,作为示例,switch包含1000个表单

case 名词 : System.out.println( 名词 ); break;

似乎有效。生成的字节码使用tableswitch指令,这意味着它甚至不应该是低效的。

当然,除非它是自动生成的代码,否则这将是不受欢迎的。

考虑替代方案,例如:

  • 一个地图/值数组(如果您的案例只是返回或产生某种值);
  • 将运行必要代码的对象的地图/数组(取决于具体条件,您可能会以这种方式使用更少的代码)。

修改

看看你的代码,似乎,因为你的所有case语句都运行完全相同类型的代码,所需要的只是Class[] index访问{1}},如:

Class[] myArray = new Class[...];
myArray[0] = Adidas.class;
//...

//instead of the switch
startActivity(new Intent(Search.this, myArray[index])); 

当然,如果有办法以其他方式生成这些类,比如你有AdidasAffin个对象,并且你运行getClass(),那会更漂亮他们,或者如果你有他们的名字列表,可以使用Class.forName

答案 3 :(得分:1)

或者您可以查看策略模式。例如:

如果现在看起来像这样:

switch (calculation type)
{
   case: Fibonacci { ... }
   case: Pithagoras { ... }
   ...
   case 104 : { ... }
}

您可以使用策略模式重构它,如下所示:

CalculationStrategy strategy = strategyFactor.getStrategy(calculation type);
strategy.doCalculation;

快乐的编码! 戴夫

答案 4 :(得分:0)

实现交换机时,可以对性能进行许多优化,否则必须列出所有交换机,直到匹配为止。

我在这里要做的是,第一个字符有一组主开关,然后嵌套开关,因此如果选择是z,则不必先循环检查每个名称

switch(FIRSTCHAR){
case A: switch(index){
        case 0: ..... break;
        etc

        }
break;

case B://do the same
}

另一种方法是将switch语句分解为更小的相等大小的语句。由于字节码的编译方式(参考Java性能调优 - shirazi)

,因此速度更快

答案 5 :(得分:0)

一个可能的appraoch是将代码移动/重新构建为“责任链模式,因为这些switch语句不是简单的返回,它们涉及一些处理等等。

我相信你也没有Guava Ranges的使用案例(换句话说,你的每个案例都是一个秘密的案例,而不是两个(不止一个)案件的常见处理。

答案 6 :(得分:0)

我不确切知道你的startActivity()方法做了什么,甚至不知道Intent对象是如何实现的,但我认为解决问题的另一种方法可能是:

  • 定义一个名为Shop超类或接口(例如);
  • 继承您的所有课程,例如AdidasAffin;
  • 为每个类调用startActivity()方法的具体实现;

例如:

public interface Shop
{
    void startActivity(Intent i);
}

然后,每个班级......

public class Adidas implements Shop
{
    public Adidas(){
        // ...
    }

    public void startActivity(Intent i)
    {
        // specific implementation
    }
}

最后,在您的客户端代码中

Shop[] shops = new Shop[]{ new Adidas(), new Affin(), ... };

for (Shop shop : shops)
{
   shop.startActivity(new Intent(Search.this));
}