// 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));
}
}}
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)
问题是for
循环结束时您的流浪分号:
for(i=0; i<objects.size(); i++); // Spot the semi-colon here
{
System.out.println(objects.get(i));
}
这意味着您的代码是有效的:
for(i=0; i<objects.size(); i++)
{
}
System.out.println(objects.get(i));
现在,这显然是错误的,因为它在循环结束i
后才使用。
如果您使用在语句i
内部for
声明的更惯用的方法,则可以在编译时发现这一点:
for (int i = 0; i < objects.size(); i++)
……到那时i
,对的调用将超出范围System.out.println
,因此您会遇到编译时错误。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句