简体   繁体   中英

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());
    }
}

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.

如果你把 return integer.Max 然后用 arraylist.size() 改变它;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM