I am attempting to search through an array list to find a value (which may reoccur) and remove all instances of that value. I also would like to remove from a separate array list, values that are at the same location. Both ArrayLists are ArrayList<String>
.
For example I am looking for the number 5 in ArrayList2:
ArrayList 1 ArrayList2
cat 1
pig 2
dog 5
chicken 3
wolf 5
Once I find the number 5, in both locations, I would like to remove dog and wolf from ArrayList1. My code has no errors but it doesn't seem to be actually removing what I am asking it.
//searching for
String s="5";
//for the size of the arraylist
for(int p=0; p<ArrayList2.size(); p++){
//if the arraylist has th value of s
if(ArrayList2.get(p).contains(s)){
//get the one to remove
String removethis=ArrayList2.get(p);
String removetoo=ArrayList1.get(p);
//remove them
ArrayList2.remove(removethis);
ArrayList1.remove(removetoo);
}
}
When I print the arrayLists they look largely unchanged. Anyone see what I am doing wrong?
When you are both looping and removing items from an array, the algorithm you wrote is incorrect because it skips the next item following each removal (due to the way in which you increment p). Consider this alternative:
int s = 5;
int idx = 0;
while (idx < ArrayList2.size())
{
if(ArrayList2.get(idx) == s)
{
// Remove item
ArrayList1.remove(idx);
ArrayList2.remove(idx);
}
else
{
++idx;
}
}
If you want to iterate over a collection and remove elements of the same collection, then you'll have to use an Iterator
, e.g.:
List<String> names = ....
List<Integer> numbers = ....
int index = 0;
Iterator<String> i = names.iterator();
while (i.hasNext()) {
String s = i.next(); // must be called before you can call i.remove()
if (s.equals("dog"){
i.remove();
numbers.remove(index);
}
index++;
}
EDIT
In your case, you'll have to manually increment a variable to be able to remove items from the other List.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With