Java中涉及ArrayList索引的问题
我正在制作一个模拟目录。单击按钮时调用此方法,并应在屏幕上显示新的学生文件。除非我超出arraylist的范围,否则它工作得很好。我知道这是一个越界异常,但我想我是用if()语句处理的。为了澄清,studentRecord是一个包含字符串数组的arraylist。这些字符串数组包含学生的姓名、除数、ID等。 这是我的密码:Java中涉及ArrayList索引的问题,java,arrays,Java,Arrays,我正在制作一个模拟目录。单击按钮时调用此方法,并应在屏幕上显示新的学生文件。除非我超出arraylist的范围,否则它工作得很好。我知道这是一个越界异常,但我想我是用if()语句处理的。为了澄清,studentRecord是一个包含字符串数组的arraylist。这些字符串数组包含学生的姓名、除数、ID等。 这是我的密码: public void previousStudent(View view){ counter--; if(counter < 0){counter =
public void previousStudent(View view){
counter--;
if(counter < 0){counter = studentRecords.size();}
tvID.setText("Student ID: " + studentRecords.get(counter)[0]);
tvName.setText("Student Name: "+ studentRecords.get(counter)[1] + " " + studentRecords.get(counter)[2]);
tvDivision.setText("Division: " + studentRecords.get(counter)[3]);
tvGender.setText("Student Gender: " + studentRecords.get(counter)[4]);
}
public void previousStudent(视图){
计数器--;
如果(计数器<0){counter=studentRecords.size();}
tvID.setText(“学生ID:+studentRecords.get(counter)[0]);
tvName.setText(“学生名:”+studentRecords.get(counter)[1]+”+studentRecords.get(counter)[2]);
tvDivision.setText(“Division:+studentRecords.get(counter)[3]);
tvGender.setText(“学生性别:+studentRecords.get(counter)[4]);
}
列表的大小不是一个可用的索引,因为列表的索引开始变为0,就像数组的索引一样。
因此,只有
studentRecords.size()-1
可用作最后一个索引,例如
counter = studentRecords.size() - 1;
要将第一个->最后一个之前的循环换行:请使用这种方式。或者,在到达第一个元素(即
0
th索引)时禁用“previous”(上一个)按钮。studentRecords.size()
仍然超出范围。您可能正在查找studentRecords.size()-1
。ArrayList类似于基于0的数组。因此,从0到ArrayList.Size()-1.OP可能希望在代码到达0
th项时从列表的开始(或结束,具体取决于您对它的看法)开始,因此只需更改counter=studentRecords.Size()代码>到计数器=studentRecords.size()-1代码>应该足够了。