IMBABOT :
Got a List of elements:
String[] temp = new String[]{"NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"};
ArrayList<String> list = new ArrayList<>(Arrays.asList(temp));
I need return to begining of the loop after removing elements from ArrayList
removing elements "NORTH"
and "SOUTH"
if they consecutive:
for (int i = 0; i < list.size() - 1 ; i++) {
if (list.get(i).equals("NORTH") && list.get(i + 1).equals("SOUTH")) {
list.remove(i);
list.remove(i);
}
if (list.get(i).equals("SOUTH") && list.get(i + 1).equals("NORTH")) {
list.remove(i);
list.remove(i);
}
the above code delete elements "NORTH"
and "SOUTH"
, and continue check elements but with this condition:
if (list.get(i).equals("SOUTH") && list.get(i + 1).equals("NORTH")) {
list.remove(i);
list.remove(i);
}
I need to back to the first condition after delete elements.
How to do it?
QuantumDeveloper :
The simplest way would be to reduce i
by 1 and the continue the loop, so in the next round, when i
gets incremented, you are back at the first if
and i
is the same as before:
for (int i = 0; i < list.size() - 1 ; i++) {
if (…) {
list.remove(i);
list.remove(i);
i--;
continue;
}
if (…) {
list.remove(i);
list.remove(i);
i--;
continue;
}
}
Or if you don't want to use the continue
statement you can use an else-if so the second condition won't be executed for i-1
:
for (int i = 0; i < list.size() - 1 ; i++) {
if (…) {
list.remove(i);
list.remove(i);
i--;
}
else if (…) {
list.remove(i);
list.remove(i);
i--;
}
}
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=299708&siteId=1