4
// 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)
1
  • Please take the time to format your code more readably in future, and provide short but complete programs demonstrating the problem. Commented Dec 5, 2013 at 7:12

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

this was the problem. simple! Thank you.
2

For loop end ; cause the disaster

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.