【问题标题】:restart and IndexOutOfBoundsException strange reason, How can I avoid this in the future?重启和 IndexOutOfBoundsException 奇怪的原因,我以后如何避免这种情况?
【发布时间】:2015-01-18 03:54:46
【问题描述】:

在 99% 的情况下正常工作,有时当应用程序被最小化并且我重新打开它时会出现异常:

java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 at java.util.ArrayList.throwIndexOutOfBoundsException

for (int i = 0; i < list.size(); ++i) 
{                  
   description.setText(list.get(i).getStreet()); //this line Exception
}

我在onStart() 方法中运行这个:

是什么原因? 以后如何避免这种情况?

【问题讨论】:

  • 你是否清除了 onPause 列表?
  • 并发修改似乎是唯一的选择。
  • @Prag'sshi 无关。
  • 试一试...可能会以某种方式..
  • @Prag'sushi "step" 表达式的值被丢弃。你不应该用“也许”来编程。

标签: java android arraylist indexoutofboundsexception


【解决方案1】:

在不同的线程中使用列表可能是一个原因。如果您使用的是未同步的 List 实现,请将其替换为同步的:

List list = Collections.synchronizedList(new ArrayList());

Vector,或CopyOnWriteList

已编辑:

感谢cmets!他们是正确的。

对我来说最简单的似乎是使用 CopyOnWriteArrayList 并使用 for-each 循环对其进行迭代。或者您可以使用此答案中的任何其他选项:Thread-safe iteration over a collection

【讨论】:

  • 这无济于事,因为同步粒度太小了。 OP需要同步整个列表遍历。
  • 使用迭代器而不是索引会导致 ConcurrentModificationException 快速失败。
  • 确实我有一个线程在后台,这可能是原因吗? java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255) at java.util.ArrayList.get
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-10
  • 1970-01-01
  • 2020-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多