Android ArrayList - 逐个添加项会导致IndexOutOfBoundsException

时间:2015-07-11 10:39:19

标签: java android arraylist indexoutofboundsexception

我使用以下函数来动画过滤列表(实际上我曾经发现某个地方,不知道在哪里):

 public void animateTo(List<T> items) {
    applyAndAnimateRemovals(items);
    applyAndAnimateAdditions(items);
    applyAndAnimateMovedItems(items);
}

private void applyAndAnimateRemovals(List<T> newItems) {
    for (int i = mListItems.size() - 1; i >= 0; i--) {
        final T item = mListItems.get(i);
        if (!newItems.contains(item)) {
            removeItem(i);
        }
    }
}

private void applyAndAnimateAdditions(List<T> newItems) {
    for (int i = 0, count = newItems.size(); i < count; i++) {
        final T item = newItems.get(i);
        if (!mListItems.contains(item)) {
            addItem(i, item);
        }
    }
}

private void applyAndAnimateMovedItems(List<T> newItems) {
    for (int toPosition = newItems.size() - 1; toPosition >= 0; toPosition--) {
        final T item = newItems.get(toPosition);
        final int fromPosition = mListItems.indexOf(item);
        if (fromPosition >= 0 && fromPosition != toPosition) {
            moveItem(fromPosition, toPosition);
        }
    }
}

 public T removeItem(int position) {
    final T item = mListItems.remove(position);
    notifyItemRemoved(position);
    return item;
}

public void addItem(int position, T item) {
    mListItems.add(position, item); // <- EXCEPTION IS THROWN HERE
    notifyItemInserted(position);
}

public void moveItem(int fromPosition, int toPosition) {
    final T model = mListItems.remove(fromPosition);
    mListItems.add(toPosition, model);
    notifyItemMoved(fromPosition, toPosition);
}

有时候我会在addItem函数中得到一个例外情况:

java.lang.IndexOutOfBoundsException: Invalid index 203, size is 201

实际上,这怎么可能发生? applyAndAnimateAdditions中的循环从0开始,如果它们不在列表中,则逐个添加项目。如何发生索引异常?

1 个答案:

答案 0 :(得分:0)

您可以添加此项以检查position是否等于或大于(>=ArrayLists size只需将项目添加到{{1}的末尾1}}。

Arraylist

所以这是你在public void addItem(int position, T item) { if(position >= mListItems.size()) mListItems.add(mListItems.size()-1, item); else mListItems.add(position, item); notifyItemInserted(position); } 进行迭代的问题,但是你要添加到newItems