是否可以将ArrayIndexOutOfBoundsException导致值更改为默认值的方法?

问题描述 投票:0回答:2

我正在尝试将导致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
      }
    }
  }
}

java arrays indexoutofboundsexception
2个回答
3
投票

类似ArrayIndexOutOfBounds之类的异常通常意味着您的代码有错误;您应将它们视为需要先“请求权限”的情况,首先需要在访问数组之前检查索引,而不是通过捕获异常来“寻求宽恕”。

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

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

1
投票

虽然创建自定义类肯定是[[cleaner,但是如果您已经有一个数组并且不关心超净体系结构,那么只需编写一个函数就可以轻松实现:

int get(int[] array, int index, int defaultValue) { if (0 <= index && index < array.length) return array[index]; else return defaultValue; }
© www.soinside.com 2019 - 2024. All rights reserved.