数组索引超出界限的循环打印内容ArrayList

use*_*394 4 java arrays loops for-loop arraylist

// ArrayList
import java.io.*; 
import java.util.*;

public class ArrayListProgram
{
public static void main (String [] args)
{
Integer obj1 = new Integer (97);
String obj2 = "Lama";
CD obj3 = new CD("BlahBlah", "Justin Bieber", 25.0, 13);

ArrayList objects = new ArrayList();

objects.add(obj1);
objects.add(obj2);
objects.add(obj3);


System.out.println("Contents of ArrayList: "+objects);
System.out.println("Size of ArrayList: "+objects.size());

BodySystems bodyobj1 = new BodySystems("endocrine");
BodySystems bodyobj2 = new BodySystems("integumentary");
BodySystems bodyobj3 = new BodySystems("cardiovascular");

objects.add(1, bodyobj1);
objects.add(3, bodyobj2);
objects.add(5, bodyobj3);

System.out.println();
System.out.println();

int i;
for(i=0; i<objects.size(); i++);
{
System.out.println(objects.get(i));
}
Run Code Online (Sandbox Code Playgroud)

}}

for循环尝试使用size()方法打印数组列表的内容.如何停止获取ArrayIndexOutOfBounds错误?

我的数组列表中有索引0-5(6个对象).

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 6, Size: 6
    at java.util.ArrayList.RangeCheck(ArrayList.java:547)
    at java.util.ArrayList.get(ArrayList.java:322)
    at ArrayListProgram.main(ArrayListProgram.java:37)
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 7

问题是for循环结束时你的分散分号:

for(i=0; i<objects.size(); i++); // Spot the semi-colon here
{
    System.out.println(objects.get(i));
}
Run Code Online (Sandbox Code Playgroud)

这意味着您的代码是有效的:

for(i=0; i<objects.size(); i++)
{
}
System.out.println(objects.get(i));
Run Code Online (Sandbox Code Playgroud)

现在这显然是错误的,因为它i 它到达循环结束正在使用.

如果你使用的声明的更地道的方式,你可以在编译时发现这i 里面for语句:

for (int i = 0; i < objects.size(); i++)
Run Code Online (Sandbox Code Playgroud)

...此时i调用的范围将超出范围System.out.println,因此您将收到编译时错误.