java.lang.IndexOutOfBoundsException: 索引 2 无效,大小为 2 [英] java.lang.IndexOutOfBoundsException: Invalid index 2, size is 2
问题描述
场景:-
我有两个 ArrayList
列表包含图像
postList 包含所选图像的位置
postList contains position of selected images
现在当我选择图像并按删除菜单时,它应该删除所选图像.
当我在 debug
中运行代码时,它工作正常并提供所需的输出.
when i am running the code in debug
,its working fine and give the desire output.
但是当我在正常模式下运行它时,它崩溃并给出上述exception
.
but when i am running it normal mode ,its crashing and giving above exception
.
if (posList.size() > 0)
{
Toast.makeText(getBaseContext(), "i value" +posList.size(),
Toast.LENGTH_SHORT).show();
for (int i = 0; i < posList.size(); i++)
appAdp.list.remove(appAdp.list.get(posList.get(i)));
appAdp.notifyDataSetChanged();
posList.clear();
Toast.makeText(getBaseContext(), "You deleted selected items",
Toast.LENGTH_SHORT).show();
}
return true;
在此处发布列表值
@Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id,
boolean checked) {
posList.add(position);
此处显示错误
appAdp.list.remove(appAdp.list.get(posList.get(i)));
logcat:-
java.lang.IndexOutOfBoundsException: Invalid index 2, size is 2
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
at java.util.ArrayList.get(ArrayList.java:304)
为什么它的行为是这样,没有得到任何线索.
why its behaving like this ,not getting any clue.
感谢您的帮助.
推荐答案
您正在尝试对 Same ArrayList 执行操作,因为当您从 ArrayList 中删除元素时,它的大小将减小,您将得到 <代码>ArrayIndexoutofBoundsException.即当您从 appAdp.list
中删除项目时,appAdp.list
的大小也会改变
You are trying to perform operation on Same ArrayList because of that when ever you are remove elemnt from the ArrayList then its size will reduce so, You'll get ArrayIndexoutofBoundsException
.
i.e when you remove item from the appAdp.list
, then the size of the appAdp.list
will also change
考虑您的列表最初是否有 3 个元素.
consider if your list has originally 3 elemnts.
你的位置在你的 posList 0,2
you have the position in your posList 0,2
然后当您从 appAdp.list
中的 0
项目中删除项目时,下次尝试时其大小将变为 2
删除位置 2
的项目,您将获得 AIOBE
then when you remove item from the 0
item from appAdp.list
, its size will become 2
for the next time when you try to remove item at position 2
, you will get AIOBE
解决方案:
将所有需要删除的项目保存在单独的 List 中,并使用 removeAll(list)
方法从您的 appAdp.list
Save all items that needs to be removed in separate List and the use removeAll(list)
method to remove items from your appAdp.list
示例:
ArrayList<yourappListtype> templist=new ArrayList<yourappListtype>();
for (int i = 0; i < posList.size(); i++)
templist.add(appAdp.list.get(posList.get(i)));
然后
appAdp.list.removeAll(templist);
这篇关于java.lang.IndexOutOfBoundsException: 索引 2 无效,大小为 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!