2

在 Java 中,我发现以下代码比相应的笨重switch语句更简洁、更易于维护:

try {
  selectedObj = new Object[] {
    objA,
    objB,
    objC,
    objD,
  }[unvalidatedIndex];
} catch (ArrayIndexOutOfBoundsException e) {
  selectedObj = objA;
}

反对

switch (unvalidatedIndex) {
  case 0:
    selectedObj = objA;
    break;

  case 1:
    selectedObj = objB;
    break;

  case 2:
    selectedObj = objC;
    break;

  case 3:
    selectedObj = objD;
    break;

  default:
    selectedObj = objA;
}

前者被认为是可接受的做法吗?我知道这不是最有效的,因为它涉及分配数组和捕获异常。unvalidatedIndex当超出范围时(尽管处理了异常),它会导致一些不受欢迎的事情吗?

如果可能的话,你会推荐一些更清洁的东西吗?

4

6 回答 6

5

你的第一种方法很好。

但是,最好先检查索引:

Object[] arr = new Object[] { ... };

if (i < 0 || i >= arr.length)
    i = 0;
selectedObj = arr[i];
于 2011-06-06T14:03:16.780 回答
2

这不是可接受的做法。异常用于错误处理,而不是程序流。例外情况也很慢。

于 2011-06-06T14:31:08.810 回答
1

怎么样

if(index < arr.length && index >= 0){
    obj = arr[index];
}else{
    obj = defaultValue;
}
于 2011-06-06T14:04:38.837 回答
1

Both are antipatterns. Just test the index for range membership yourself. There might be a way to use an enum in many actual cases.

于 2011-06-06T19:07:19.070 回答
1

Personally, though I have no doubt some will disagree, I would do:

switch (unvalidatedIndex) {
    case 0 : selectedObj = objA; break;
    case 1 : selectedObj = objB; break;
    case 2 : selectedObj = objC; break;
    case 3 : selectedObj = objD; break;
    default: selectedObj = objA; break;
    }

It's clean, compact, efficient, and really easy to understand.

I would hesitate to include the case 0, that being the default case.

于 2011-06-06T19:28:46.457 回答
-1
    int index = 4;

    ArrayList<String> myObjects = Lists.newArrayList("a", "b", "c", "d");
    Object o = index  < myObjects.size() && index >= 0 ? myObjects.get(index) : null;
    System.out.println(o);

列表来自番石榴。

于 2011-06-06T14:10:14.610 回答