有没有办法将导致值的 ArrayIndexOutOfBoundsException 替换为某个默认值?

Is there a way to replace an ArrayIndexOutOfBoundsException causing value to some default value?

我正在尝试将导致 ArrayIndexOutOfBounds 的值替换为 0。

我希望得到的输出是:

0
10
20
30
40
0
0
0
0
0

有办法实现吗?

请注意,我不想以打印为目的(我可以通过在 catch 块中执行 System.out.println("0") 来实现。

public class test {
  int[] array;

  @Test
  public void test() {
    array = new int[5];
    for (int i = 0; i < 5; i++) {
      array[i] = i;
    }

    for(int i = 0; i < 10; i++) {
      try {
        System.out.println(array[i] * 10);
      }
      catch(ArrayIndexOutOfBoundsException e) {
        //code to replace array[i] that caused the exception to 0
      }
    }
  }
}

像 ArrayIndexOutOfBounds 这样的异常通常意味着你的代码有错误;您应该将它们视为需要先 "ask permission" 通过在访问数组之前检查索引而不是 "seek forgiveness" 通过捕获异常来处理的情况。

面向对象编程就是封装你想要的行为。数组不会以这种方式运行,因此您不能为此目的直接使用数组。但是,如果您想要 确实 以这种方式运行的东西(即当您访问不存在的索引时它 returns 是默认值),那么请发明您自己的东西类型那。例如:

public class DefaultArray {
    private final int defaultValue;
    private final int[] array;

    public DefaultArray(int length, int defaultValue) {
        this.array = new int[length];
        this.defaultValue = defaultValue;
    }

    public int get(int i) {
        // ask permission!
        if(i >= 0 && i < array.length) {
            return array[i];
        } else {
            return defaultValue;
        }
    }
    public void set(int i, int value) {
        array[i] = value;
    }
    public int length() {
        return array.length;
    }
}

用法:

DefaultArray arr = new DefaultArray(5, 0);
for(int i = 0; i < 5; i++) {
    arr.set(i, i);
}
for(int i = 0; i < 10; i++) {
    System.out.println(arr.get(i) * 10);
}

输出:

0
10
20
30
40
0
0
0
0
0

虽然自定义class肯定更干净,但如果您已经有一个数组并且不关心超级干净的架构,那么它是微不足道的只需创建一个函数即可轻松完成:

int get(int[] array, int index, int defaultValue) {
    if (0 <= index && index < array.length) return array[index];
    else return defaultValue;
}