For example, I have a list of strings say:
List<String> strs = new ArrayList<String>();
strs.add("A");
strs.add("B");
strs.add("C");
strs.add("D");
I want to loop over the list and get some elements, but at the same time, I want to remove some elements. Let's say:
for (int i = 0; i < strs.size(); i++) {
String element = strs.get(i);
System.out.println(element);
strs.remove("A")
}
In the above example, element would be "A", "C", "D". But what I want is "A", "B", "C", "D". The above code is just an example, there could be other elements I want to remove, such as:
for (int i = 0; i < strs.size(); i++) {
String element = strs.get(i);
System.out.println(element);
if (condition A) { strs.remove("A"); }
if (condition B) { strs.remove("B"); }
if (condition D) { strs.remove("D"); }
}
In this case, the size of the List strs
would change depends on different conditions. And sometimes element
jump from "A" to "C" without "B". What I have tried so far is created a list of indexes in my notebook. I know that remove element "A" will make the for loop ignore "B", but when this comes to other cases, the indexes don't work anymore. Is there a final algorithm or solution that can check every element inside the for loop?
Notice: Without using Iterator, List.removeAll, or i-- (Since I sometimes get Time Limit Exceed when use i--).