KarmaCoding KarmaCoding - 2 months ago 13
Java Question

ArrayList ArrayIndexOutOfBoundsException while deleting items from ArrayList

I have two arraylists listA and listB ;

what i want to do is , i want to delete the same items from both list which are occuring in listA and listB;

i am facing the ArrayIndexOutOfBoundsException exception here..

for (int i = 0; i < listA.size(); i++) {
for (int j = 0; j < listB.size(); j++) {
if (listA.get(i).equals(listB.get(j))) {
listA.remove(i);
listB.remove(j);

}
}
}

Answer

made some changes in your code

for (int i = 0; i < listA.size(); i++) {
            for (int j = 0; j < listB.size(); j++) {
                if (listA.get(i).equals(listB.get(j))) {
                    listA.remove(i);
                    listB.remove(j);
                    i = i - 1;
                    j = j - 1;
                }
            }
        }
Comments