Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ArrayList search and remove

Tags:

java

arraylist

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?

like image 509
Stephopolis Avatar asked Dec 07 '22 12:12

Stephopolis


2 Answers

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;
  }
}
like image 108
a_a_t Avatar answered Dec 24 '22 20:12

a_a_t


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.

like image 23
bpgergo Avatar answered Dec 24 '22 21:12

bpgergo