Trying to solve this problem using Iterator and ListIterator - getting "ConcurrentModificationException".
package com.codegym.task.task07.task0716;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
/*
R or L
*/
public class Solution {
public static void main(String[] args) throws Exception {
ArrayList<String> list = new ArrayList<String>();
list.add("rose"); // 0
list.add("love"); // 1
list.add("lyre"); // 2
list = fix(list);
for (String s : list) {
System.out.println(s);
}
}
public static ArrayList<String> fix(ArrayList<String> list) {
// write your code here
Iterator<String> itr = list.iterator();
ListIterator<String> listItr = list.listIterator();
while(itr.hasNext()){
String nextElement = itr.next();
if (nextElement.contains("r") && nextElement.contains("l")){
}
if (nextElement.contains("r") && !nextElement.contains("l")){
itr.remove();
} // Till the point to remove the element, program is working fine.
// Below if loop is throwing error
if (nextElement.contains("l") && !nextElement.contains("r")){
listItr.add(nextElement); // tried all sort of combination here to add elements used list.add(nextElement) also listItr.add(list.get(listItr.nextIndex())) - nothing worked.
}
// Tried with separate while loop, didn't work :(
/* while (listItr.hasNext()){
if (nextElement.contains("l") && !nextElement.contains("r")){
listItr.
}
}*/
}
return list;
}
}