ArrayList的While循环导致IndexOutOfBoundsException异常

4
我将尝试编写一种方法,使用锦标赛式比较来确定数组列表的最大值。然而,我猜想我对while循环的理解有误,因为我无法获得所需的输出,反而会出现IndexOutOfBoundsException异常。
以下是我的代码:
import java.util.*;
public class TournamentMax {

public static <T extends Comparable<? super T>> ArrayList<T> tournament(ArrayList<T> tournamentArrayList) {
    ArrayList<T> winners = new ArrayList<T>();
    int n = tournamentArrayList.size();
    int upper;

    if (n % 2 != 0 ){ // if size is odd
        winners.add(tournamentArrayList.get(n));
        upper = n - 2;
    }

    else{  // if size is even
        upper = n - 1;
    }

    for (int index = 0; index < upper; index+=2){


        T winner = max(tournamentArrayList.get(index), tournamentArrayList.get(index + 1));
         System.out.println("Comparison between: " + tournamentArrayList.get(index) + " and " + tournamentArrayList.get(index + 1) );
         System.out.println("Winner was: " + winner);
        winners.add(winner);
    }

    return winners;     
}

public static <T extends Comparable<? super T>> T max (T obj1, T obj2){
    if (obj1.compareTo(obj2) > 0){
    return obj1;    
    }
    else return obj2;
}

public static <T extends Comparable<? super T>> ArrayList<T> maximum(ArrayList<T> tournamentArrayList){
    ArrayList<T> maximum = new ArrayList<T>();
    for (int i = 0; i < tournamentArrayList.size(); i++){
        maximum.add(tournamentArrayList.get(i));
    }
    while (maximum.size() > 1){
    System.out.println("maximum before tournament" + maximum);
    maximum = tournament(maximum);
    System.out.println("maximum after tournament and the one returned" + maximum);
    }   
    return maximum;


}

}

我知道问题出在这部分代码中:

while (maximum.size() > 1){
    System.out.println("maximum before tournament" + maximum);
    maximum = tournament(maximum);
    System.out.println("maximum after tournament and the one returned" + maximum);

在我的脑海中,我试图让ArrayList在被传回比赛方法之前不断地传递,直到ArrayList只包含一个项目,这应该是最大的。更令我困惑的是,循环第一次执行,然后抛出异常。我猜我没有正确使用递归或其他什么,但如果有人能指点我正确的方向,那将不胜感激! 我正在使用它作为测试客户端:
public static void main(String... args) {
ArrayList<Integer> test = new ArrayList<Integer>();
test.add(12);
test.add(10);
test.add(65);
test.add(4);
test.add(78);
test.add(89);
test.add(99);
test.add(96);
test.add(24);
test.add(22);
ArrayList<Integer> testWinners = tournament(test);
System.out.println(testWinners);
ArrayList<Integer> testMaximum = maximum(test); 
System.out.println(testMaximum);


}

这个例子代码很多,如果你不想看的话可以直接跳到Sbodd的回答,他解释了“由于列表索引从0开始,因此列表中的最后一个元素位于索引size() - 1处”的含义。 - HRVHackers
1个回答

4
以下两行代码总是会抛出 IndexOutOfBoundsException 异常 - 当数组大小为奇数时发生:
int n = tournamentArrayList.size();
//...
winners.add(tournamentArrayList.get(n));

由于列表索引从0开始,列表中的最后一个元素位于索引size() - 1处。

这也解释了为什么循环第一次执行得很好。此时列表仍然具有偶数大小。 - Robin
当然啦!我现在觉得有点傻呢...感谢你发现了这个错误! - Stavrosnco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接