且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

java.lang.IndexOutOfBoundsException:无效指数2,大小为2

更新时间:2023-09-14 14:30:22

您正在尝试在因为同ArrayList中执行操作时,你永远是移除ArrayList中elemnt那么它的规模将减少的话,您将获得 ArrayIndexOutOfBoundsException异常
       即当您从 appAdp.list ,那么大小的 appAdp.list 也将改变删除项目p>

考虑,如果您的列表中有3最初elemnts。

你有你的posList 0,2的位置

然后当您从 0 项目从 appAdp.list 删除项目,其规模将成为 2 当你试图在位置删除项下一次 2 ,您将获得 AIOBE

解决方案:

保存,需要在单独的列表以及使用的removeAll(名单)方法从你的 appAdp.list

例如:

 的ArrayList< yourappListtype> templist =新的ArrayList< yourappListtype>();
的for(int i = 0; I< posList.size();我++)
        templist.add(appAdp.list.get(posList.get(I)));

然后

  appAdp.list.removeAll(templist);

Scenario:-

I have two ArrayList

list contains images

postList contains position of selected images

now when ever i am selecting the images and press delete menu ,it should delete the selected images .

when i am running the code in debug ,its working fine and give the desire output.

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;

postList values here

@Override
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id,
                boolean checked) {
            posList.add(position);

error showing here

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.

Thanks for any help.

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

consider if your list has originally 3 elemnts.

you have the position in your posList 0,2

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

Solution:

Save all items that needs to be removed in separate List and the use removeAll(list) method to remove items from your appAdp.list

Example:

ArrayList<yourappListtype> templist=new ArrayList<yourappListtype>();
for (int i = 0; i < posList.size(); i++)
        templist.add(appAdp.list.get(posList.get(i)));

And then

appAdp.list.removeAll(templist);