How do I resolve ConcurrentModificationException
from the below program .
I need a list where first element is "Znk"
, and then the sorted listed following it.
I understand, I am getting this because I am adding and removing in the same iteration . But how do I resolve this and get the desired output.
public class ListSwapIndex {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> swapIndex = new ArrayList<String>();
ArrayList<String> swapIndextemp = new ArrayList<String>();
swapIndex.add("Ank");
swapIndex.add("Znk");
swapIndex.add("Bnk");
swapIndex.add("Dnk");
swapIndex.add("Enk");
swapIndex.add("Lnk");
for (String string : swapIndex) {
if(string.equals("Znk")){
swapIndextemp.add(string);
swapIndex.remove(string);
}
}
swapIndextemp.addAll(swapIndex);
System.out.println(swapIndextemp);
}
}