【问题标题】:ArrayList IndexOutOfBoundsException at position 0位置 0 处的 ArrayList IndexOutOfBoundsException
【发布时间】:2015-02-15 22:20:17
【问题描述】:

我在一个 Android 应用程序中遇到了一个奇怪的问题。 我有一个 ArrayList,我尝试使用 get(0) 获取第一个项目。 但是应用程序有时会因为 IndexOutOfBoundsException 而崩溃。

代码:

int currentItemPosition = 0;
if(!mArrayList.isEmpty()) {
   currentItem = mArrayList.get(currentItemPosition);
}

这怎么可能?

日志:

java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
...

【问题讨论】:

  • mArrayList 是否被多个线程访问/更新?
  • 这是您正在运行的实际代码还是演示?
  • 唯一可能的选择是在 empty() 检查和 ArrayList.get() 之间修改列表。您应该寻找修改列表的其他线程。当您在 Android 应用程序中运行代码时,可能有些东西正在修改您的列表。更多关于创建列表以及何时抛出异常的代码可能会有所帮助
  • isEmpty() 不会返回 true,如果 mArrayListnull(从不实例化)。
  • 试试这个:int currentItemPosition = 0; synchronized(mArrayList){ if(!mArrayList.isEmpty()) { currentItem = mArrayList.get(currentItemPosition); } }

标签: java android arraylist


【解决方案1】:

如上所述(单ArrayList,单线程,&c),这个问题似乎有点“不可能”。但是,如果这 (http://pastebin.com/2fYnbG9b) 是您的实际 sn-p:

private void showFirstItemOfPage() {
    mCurrentBlockItem = 0;
    if(mBlocksList.get(mPager.getCurrentItem()) != null && !mBlocksList.get(mPager.getCurrentItem()).isEmpty())
    {
        addSingleItem(mBlocksList.get(mPager.getCurrentItem()).get(mCurrentBlockItem));
    }      
}

也许答案是mBlocksList 实际上是空的?您不会检查isEmpty() 中的那个 列表,而只是检查它包含的列表。

【讨论】:

  • 正如我在 cmets 中所说的。 “问题是,我无法重现此崩溃 - 但开发人员控制台中的崩溃日志告诉我,在这一行中抛出了 IndexOutOfBoundsException”我对 mBlocklist 项目进行了空检查 - 如果 mBlocklist 会抛出 OOBException。但是崩溃日志是指 addSingleItem 这一行。
猜你喜欢
  • 2015-04-15
  • 2018-07-24
  • 2016-11-07
  • 2016-03-22
  • 2016-04-04
  • 2018-12-03
  • 1970-01-01
  • 2014-01-14
  • 2015-11-07
相关资源
最近更新 更多