I’m trying to remove a 2d arraylist from another 3d arraylist.
I mean, delete all the ar1[][] from ar2[][][]
I can’t understand why my code is not deleting all of them:
public void removeSame(ArrayList<ArrayList<String>> ar1,ArrayList<ArrayList<ArrayList<String>>> ar3)
{
for(int k=0;k<ar3.size();k++)
for(int j=0;j<ar3.size();j++)
if(isSame(ar1,ar3.get(k)))
{
ar3.remove(k);
}
}
public boolean isSame(ArrayList<ArrayList<String>> ar1,ArrayList<ArrayList<String>> ar2)
{
for(int k=0;k<ar2.size();k++)
for(int j=0;j<ar2.size();j++)
if(!ar1.get(k).get(j).equals(ar2.get(k).get(j)))
return false;
return true;
}
I can see one issue when there are more than one occurrences of
ar1inar3. After first removal ofar1fromar3usingar3.remove(k);, the index and size ofar3ArrayList is changed ie. both size and indexes are reduced by one. Now when you continue your loop, it will skip one element in between as you continue using the original index. Also your innerforloop seems to be unnecessary.There are two ways to resolve the issue.
Option1: User List#iterator i.e.
Option2: After removal, reduce the index i.e.
kvalue by one before continuing e.g.