将ArrayList转换为2D数组-返回ArrayOutOfBounds



我需要创建一个学生列表,并将他们转换为座位表(特定长度和宽度的二维数组(。这是我的代码:

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中再添加两个学生,ArrayList类(rangeCheck和get(中的错误就消失了。为什么解决了错误,为什么最后两个错误仍然存在?我已经仔细检查了代码背后的逻辑,并用与ArrayList大小相同的1D数组替换了2D数组,但我得到了相同的错误。

在这里我可以看到问题

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.*/
}
}

最新更新