将ArrayList转换为2D数组-返回ArrayOutOfBounds [重复]

问题描述 投票:-1回答:1

我需要创建一个学生列表并将其转换为座位表(特定长度和宽度的2d数组)。这是我的代码:

public class SeatingChart {
  Student seats[][];
  public SeatingChart(List <Student> studentList, int rows, int cols) {
    seats = new Student[rows][cols];
    for (int i = 0; i < cols; i++) { //Assigns Students in Column by Row order
        for (int j = 0; j < rows; j++) {
            if (i*rows+j > studentList.size() - 1) {
                seats[i][j] = null; //Occupies remaining `seats` with null
            }
            seats[i][j] = studentList.get(i*rows+j); //Finds an error with this line
        }
    }
}

public class Tester {
  public static void main (String[] args) {
    List <Student> classroom = new ArrayList<Student>();
    classroom.add(new Student("Anna", 3));
    SeatingChart sc = new SeatingChart(classroom, 2, 2); //Finds an error with this line
  }
}

public class Student {
  //assigns Name and number of absences for each student
}

此返回:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
    at java.util.ArrayList.rangeCheck(ArrayList.java:657)
    at java.util.ArrayList.get(ArrayList.java:433)
    at stud2.SeatingChart.<init>(SeatingChart.java:14)
    at stud2.SeatingChartTester.main(SeatingChartTester.java:12)

但是,一旦我在classroom中再增加2个学生,属于ArrayList类的错误(rangeCheck和get)就消失了。为什么错误得以解决,为什么最后两个错误仍然存​​在?我仔细检查了代码背后的逻辑,并用与ArrayList大小相同的1D数组替换了2D数组,但我遇到了相同的错误。

java arrays arraylist indexoutofboundsexception indexoutofrangeexception
1个回答
1
投票

在这里我可以看到问题

  List <Student> classroom = new ArrayList<Student>();
classroom.add(new Student("Anna", 3)); //so size of class room is 1

现在您正在执行此操作

  SeatingChart sc = new SeatingChart(classroom, 2, 2); // which says class has two rows and two colums means 4 students which is not true because your list has only one

现在通知

 for (int i = 0; i < cols; i++) { 
    for (int j = 0; j < rows; j++) { // the first iteration in this loop will go fine
        if (i*rows+j > studentList.size() - 1) {
            seats[i][j] = null;
        }
        seats[i][j] = studentList.get(i*rows+j);
 /* but when j is one and i is 0 this expression resolves to i*rows + j == 0*2 + 1 = 1
   means you're saying studentList.get(1) , but list has only one student which is at 
   index 0 , that  
   is why you're getting java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 cuz 
   index 
   is 1 in the get(1) and size is also 1 means noting at index 1.*/
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.