Calvin Kinzie
Calvin Kinzie

Reputation: 113

IndexOutOfBoundsException at Index: 4, Size: 4 when adding elements to an ArrayList

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 4
    at java.util.ArrayList.rangeCheck(ArrayList.java:653)
    at java.util.ArrayList.get(ArrayList.java:429)
    at seatOrganiser.Arranger.breakIfTwo(Arranger.java:30)
    at seatOrganiser.Arranger.main(Arranger.java:17)

When I click on the ArrayList.java:653 or ArrayList.java:429, I get a "653 is not a valid line number in java.util.arraylist."

I'm writing an application to make a seating chart based on excel data, and I have an IndexOutOfBoundsException error when adding elements to an ArrayList of strings. I get that this is caused by calling an index that is outside of the ArrayList's range, but why is it out of the range?

The code:

public static void breakIfTwo(ArrayList<ArrayList<HSSFCell>> firstShowStudents, boolean multipleNeeded) {
    ArrayList<HSSFCell> list;
    list = firstShowStudents.get(0);
    ArrayList<String> temporary = new ArrayList<String>();
    temporary.add(list.get(4).getStringCellValue());

    for (int i = 1; i < firstShowStudents.size(); i++) {
        list = firstShowStudents.get(i);
        temporary.add(list.get(4).getStringCellValue());
    }
}

Upvotes: 3

Views: 14920

Answers (2)

rajeev ranjan
rajeev ranjan

Reputation: 230

if you put return integer.Max then change this with arraylist.size();

Upvotes: 0

lordoku
lordoku

Reputation: 1112

It's out of range because Java is 0 indexed. In other words an array with a length of 4 is indexed as:

0, 1,2,3.

So 4 is greater than the max index of 3.

Excel, on the other hand, is 1 indexed, meaning that an array with a length of 4 is indexed as: 1,2,3,4.

Upvotes: 3

Related Questions