0

So I am trying to create this loop that can remove a specific character in a given string from an arraylist. The problem is when there are two of the same characters in a row it will miss the second one because when the first is removed the second one is pushed down a spot in the array list. This is what I have so far. Anyone know how to fix this? I am still a beginner at java so any help would be appreciated.

ArrayList<Character> list = new ArrayList();
String string = "BuBBuopB";
for(int i=0;i<string.length();i++) 
list.add(string.charAt(i));
System.out.println("BEFORE: " + list);


for(int i=0;i<list.size();i++) 
if(list.get(i).equals('B'))
    list.remove(i);
System.out.println("AFTER: " + list);

what is printed from this example is AFTER: [u, B, u, o, p] when I want it to be AFTER: [u, u, o, p]

John Smith
  • 37
  • 1
  • 8
  • Your list skips the next one because when you remove a letter, the rest shift to accommodate, so you are moving forward a letter at the same time the rest of the string moves back a letter. – Misys Apr 18 '17 at 16:15
  • 1
    You should either use an iterator or `list.removeIf(c -> c == 'B');` – assylias Apr 18 '17 at 16:16
  • While removing element you are shifting elements after it to the left which means new element will be placed at position of removed one. But in your loop you are already moving to next index without texting that new element. To solve it either don't call `i++` after removal, or start iterating from other end. Or even better use `Iterator#remove`. – Pshemo Apr 18 '17 at 16:17
  • Use an Iterator to iterate through the list, and call iterator.remove() to remove the current element. – JB Nizet Apr 18 '17 at 16:17
  • for(int i=0;i – RAZ_Muh_Taz Apr 18 '17 at 16:22

1 Answers1

5

Rather than using an int-based for loop to iterate over your collection, use an Iterator instead:

Iterator<Character> iter = list.iterator();
while(iter.hasNext()) {
    if(iter.next().equals('B')) {
        // Remove the last thing returned by next()
        iter.remove();
    }
}
VeeArr
  • 6,039
  • 3
  • 24
  • 45