【问题标题】:IndexOutOfBoundException while adding in queueList在 queueList 添加时出现 IndexOutOfBoundException
【发布时间】:2017-04-02 01:02:49
【问题描述】:
private void removeQueue(Queue queue)
    {
        queue.setTodoDeleted(false);
        if ( queueIndex != -1) {
            this.queueList.add(queueIndex , queue);
            mItemManger.closeAllItems();
        }
    }

其中 queueList 是 queue ArrayList queuelist 的 ArrayList。

问题:在 queueList 中添加时,索引为 2,列表大小为 1,所以 IndexOutOfBoundException 会在 Line
this.queueList.add(queueIndex , queue) 处抛出。

避免这种情况的最佳方法是什么?在高级,谢谢

【问题讨论】:

  • queueIndex 来自哪里?它应该遵循queue 大小...
  • 索引为 2,列表大小为 1,您正在尝试获取不存在的元素

标签: java arrays list arraylist indexoutofboundsexception


【解决方案1】:

为避免出现 IndexOutOfBounds 问题,请在执行操作之前检查您要使用的实际大小和索引。

if ( queueList.size()>queueIndex)
{
   this.queueList.add(queueIndex , queue);
}
// Add else part if needed

【讨论】:

  • 谢谢,venkat 使用它工作正常,没有抛出异常。
  • @Swift 你应该试着找出为什么 queueIndex 大于实际大小。
猜你喜欢
  • 1970-01-01
  • 2012-03-25
  • 2021-12-25
  • 1970-01-01
  • 1970-01-01
  • 2016-09-15
  • 1970-01-01
  • 1970-01-01
  • 2020-06-02
相关资源
最近更新 更多