Android ArrayList的IndexOutOfBoundsException [英] IndexOutOfBoundsException with Android ArrayList

查看:101
本文介绍了Android ArrayList的IndexOutOfBoundsException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个非常烦人的问题,一些代码抛出了IndexOutOfBoundsException,我真的不明白为什么. logcat指向以下代码的"addTimetableItem",这将在以下内容中进行详细说明:

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 following code which ill explain more on:

if(sortedFridayTimes.size()>0){
    insertDay("Friday");
    for(int i=1; i<sortedFridayTimes.size()+1;i++){
        addTimetableItem(sortedFridayTimes.get(i));
    }
}

"sortedFridayTimes"是一个ArrayList,其中包含我自己的时间表条目"对象,这些对象已经按顺序进行了排序.首先检查大小,以查看是否有任何对象,然后检查是否存在"insertDay",这将为标题创建一个新的textview并将其添加到布局中(这很好..). 在for循环内,想法是将arraylist中的所有对象添加到布局中.现在我知道"addTimetableItem"代码已经通过ive测试,但是我的问题是我似乎无法从arraylist中获取最后一个对象.如果我声明for循环仅针对

"sortedFridayTimes" is an ArrayList containing my own "Timetable Entry" objects which I have sorted into order already. First the size is checked to see if there are any objects and if there is then "insertDay" runs which creates a new textview for a title and adds it to the layout (This works fine..). Inside the for loop the idea is to then add all the objects from the arraylist into the layout. Now I know that the "addTimetableItem" code works as ive tested it already, but my problem is that i cant seem to get the last object out of the arraylist. If I declare the for loop to only run for

"i<sortedFridayTimes.size()" 

然后程序运行正常,但是我没有找到数组列表中的最后一个条目,因为我已经调试并监视了变量,所以我知道它存在.如上所示,在添加"+1"后,我现在得到了IndexOutOfBoundsException,我真的不知道为什么.就像我说的那样,我已经调试了,而且我知道要尝试指向的arraylist中存在一个条目,但是它崩溃了.如果需要,我可以提供更多代码,但是有人有什么想法吗?

then the program runs fine but I don't get the last entry in the arraylist which I know exists because I've debugged and watched my variables. On adding the "+1" as shown above I now get the IndexOutOfBoundsException and I really don't know why. As I've said, I've debugged and I know that an entry exists in the arraylist where I'm trying to point to, but it just crashes. I can provide more code if needs be, but does anyone have any ideas please?

推荐答案

i<sortedFridayTimes.size()+1

您正在循环经过数组中的最后一个元素.为什么+1?

You are looping past the last element in the array. Why the +1?

如果数组中有N个元素,则这些元素从索引0N-1.

If there are N elements in the array, then the elements are from indexes 0 through to N-1.

应该是:

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

这篇关于Android ArrayList的IndexOutOfBoundsException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆