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

标签 java arrays indexoutofboundsexception

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

我希望得到的输出是:

0
10
20
30
40
0
0
0
0
0

有办法实现吗?

请注意,我不希望将此用于打印目的(我可以通过在 catch block 中执行 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 这样的异常通常意味着您的代码中存在错误;您应该将它们视为需要在访问数组之前通过检查索引来“请求许可”的情况,而不是通过捕获异常来“寻求宽恕”。

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

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

关于java - 有没有办法将 ArrayIndexOutOfBoundsException 导致值替换为某个默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58811684/

相关文章:

c - 如何在C中访问指针到指针的值?

php - 带有键的 array_pop()

java - ArrayindexOutOfBoundsException 与最佳二叉搜索树实现 java

arrays - 移动/重新排序数组中的特定项目 - SwiftUI

java - Java 中数组列表出现越界异常错误

java - 从 BufferedImage 渲染 Sprite 时出现问题

java - 使用 Hibernate 处理不同的用户类型

java - 查找树中的最大元素

java - 在intellij IDEA中找不到JDK x64

java - SparkContext setLocalProperties