问题描述
限时送ChatGPT账号..我遇到了一个非常烦人的问题,一些代码抛出了 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",它会为标题创建一个新的文本视图并将其添加到布局中(这很好用..).在 for 循环内部,想法是将 arraylist 中的所有对象添加到布局中.现在我知道addTimetableItem"代码可以像我已经测试过的那样工作,但我的问题是我似乎无法从数组列表中获取最后一个对象.如果我声明 for 循环只运行 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,我真的不知道为什么.正如我所说,我已经调试过并且我知道我试图指向的数组列表中存在一个条目,但它只是崩溃了.如果需要,我可以提供更多代码,但有人有任何想法吗?
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
个元素,则元素从索引0
到N-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屋!
更多推荐
[db:关键词]
发布评论