Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array Index Out of Bounds For Loop Print Contents 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));
}

} }

The for loop is attempting to print the contents of the array list using the size() method. How can I stop getting an ArrayIndexOutOfBounds error?

I have indexes 0-5 in my array list (6 objects).

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)
like image 254
user2990394 Avatar asked Jan 11 '23 18:01

user2990394


1 Answers

The problem is your stray semi-colon at the end of the for loop:

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

That means your code is effectively:

for(i=0; i<objects.size(); i++)
{
}
System.out.println(objects.get(i));

That's now more obviously wrong, because it's using i after it's reached the end of the loop.

You could spot this at compile-time if you used the more idiomatic approach of declaring i inside the for statement:

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

... at that point i would be out of scope in the call to System.out.println, so you'd get a compile-time error.

like image 117
Jon Skeet Avatar answered Jan 30 '23 19:01

Jon Skeet