Search code examples
javaswitch-statementindexoutofboundsexceptionanonymous-arrays

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 the 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?


Solution

  • 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];