带有 Android ArrayList 的 IndexOutOfBoundsException

编程入门 行业动态 更新时间:2024-10-21 03:45:22
本文介绍了带有 Android ArrayList 的 IndexOutOfBoundsException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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个元素,则元素从索引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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-16 10:11:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/884978.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Android   ArrayList   IndexOutOfBoundsException

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!