IndexOutOfBoundsException with Android ArrayList

后端 未结 3 1222
误落风尘
误落风尘 2021-01-26 14:30

I\'ve got a very annoying problem with some code throwing an IndexOutOfBoundsException and I really cannot understand why. The logcat points to the \"addTimetableItem\" of the f

3条回答
  •  我在风中等你
    2021-01-26 14:50

    You should accept @Tim's or @Graham's answer, this is just an addendum. They're correct about your size()+1 going past the end of the array.

    If you're having difficulty using indexes to properly get everything out of the list, you can also try using a for-each loop (depending on the version of the Android SDK you're using). I'm assuming sortedFridayTimes is a list of class TimetableItem since you don't specify.

    So this:

    if(sortedFridayTimes.size()>0){
        insertDay("Friday");
        for(int i=1; i

    Becomes this:

    if(!sortedFridayTimes.isEmtpy()){
        insertDay("Friday");
        for(TimetimeItem item : sortedFridayTimes){
            addTimetableItem(item);
        }
    }
    

    A little cleaner if you don't actually need to use i anywhere.

提交回复
热议问题