【问题标题】:Array Index Out of Bounds For Loop Print Contents ArrayList循环打印内容ArrayList的数组索引越界
【发布时间】:2013-12-22 00:22:17
【问题描述】:
// 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)

【问题讨论】:

  • 请在以后花时间格式化您的代码,使其更具可读性,并提供简短但完整的程序来演示问题。

标签: java arrays loops for-loop arraylist


【解决方案1】:

问题是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 inside for 语句,您可以在编译时发现这一点:

for (int i = 0; i < objects.size(); i++)

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

【讨论】:

  • 这是问题所在。简单的!谢谢。
【解决方案2】:

for循环结束;造成灾难

 for(i=0; i<objects.size(); i++); // remove ; from here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-21
    • 2015-01-28
    • 2013-07-27
    • 2019-04-03
    • 2011-09-27
    相关资源
    最近更新 更多