为什么我在这个程序中得到了 IndexOutOfBoundException?

Why did I get IndexOutOfBoundException in this program?

此程序使用 ArrayList class,我在 运行 时出现异常,这是什么问题?我找不到任何逻辑问题!

public static ArrayList<Double> differenceArray(ArrayList<Double> a, double avg) {

    ArrayList<Double> temp = new ArrayList<>(a.size());
    for (int i = 0; i < a.size(); i++) {
        temp.set(i, avg - a.get(i));

    }
    return temp;
}

public static void showScoresDiff(ArrayList<Double> a) {

    fillArray(a);
    double avg = computeAvg(a);
    double diff;
    for (int i = 0; i < a.size(); i++) {

        diff = avg - a.get(i);

        System.out.println("the diffrence between the avarege " + avg + " and the element " + a.get(i) + " is " + Math.abs(diff));
    }

    System.out.println("\n");

    ArrayList<Double> newArray = differenceArray(a, avg);
    for (int i = 0; i < a.size(); i++) {
        System.out.println("The " + (i + 1) + "th " + "element of the difference array is: " + newArray.get(i));
    }
}

{ 这是输出: ]1

Blockquote

问题出在以下几行:

 ArrayList<Double> temp = new ArrayList<>(a.size());
    for (int i = 0; i < a.size(); i++) {
        temp.set(i, avg - a.get(i));

语句 ArrayList<Double> temp = new ArrayList<>(a.size()) 没有用与 a.size() 一样多的元素初始化 temp 即在该语句之后 temp 的大小仍然是 0被执行。

下面给出的是 ArrayList(int initialCapacity)description:

Constructs an empty list with the specified initial capacity.

因为 temp 的大小是 0,语句 temp.set(i, avg - a.get(i)) 将抛出 IndexOutOfBoundsException.

如果想让tempa的元素初始化,可以按如下方式进行:

ArrayList<Double> temp = new ArrayList<>(a);

现在,您可以将元素设置为索引,a.size() - 1

--或--

如果您只是想向 temp 添加一些内容,您可以使用 ArrayList#add(E e),例如temp.add(5.5).