开发者

Anonymous array indexing instead of a switch statement?

In Java, I find the following code much cleaner and easier to maintain than the corresponding bulky switch statement:

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

opposed to

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;
}

Is th开发者_JS百科e former considered an acceptable practice? I am aware that it's not the most efficient one as it involves allocating an array and catching an exception. Would it cause something undesirable when unvalidatedIndex is out of range (although the exception is handled)?

If possible, would you suggest something cleaner?


Your first approach is fine.

However, it is better to check the index first:

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

if (i < 0 || i >= arr.length)
    i = 0;
selectedObj = arr[i];


It is not an acceptable practice. Exceptions are for errors handling, not for program flow. Also exceptions are VERY SLOW.


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


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.


How about

if(index < arr.length && index >= 0){
    obj = arr[index];
}else{
    obj = defaultValue;
}


    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);

Lists comes from Guava.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜