I have tried to remove the list from a vector like below.
public class StringVectorTest {
private final List<String> stringVector = new Vector<String>();
@Test
public void listRemoveTest(){
List<String> list = stringVector.subList(0, 2);
stringVector.removeAll(list);
Assert.assertEquals(stringVector.size(), 3);
}
@Before
public void fillList(){
stringVector.add("ABC");
stringVector.add("DEF");
stringVector.add("GEH");
stringVector.add("IJK");
stringVector.add("LMN");
}
}
while i run the test i am getting the below error
java.util.ConcurrentModificationException
at java.util.SubList.checkForComodification(AbstractList.java:752)
at java.util.SubList.listIterator(AbstractList.java:682)
at java.util.AbstractList.listIterator(AbstractList.java:284)
at java.util.SubList.iterator(AbstractList.java:678)
at java.util.AbstractCollection.contains(AbstractCollection.java:82)
at java.util.Collections$SynchronizedCollection.contains(Collections.java:1563)
at java.util.AbstractCollection.removeAll(AbstractCollection.java:336)
at java.util.Vector.removeAll(Vector.java:853)
I know that i have to use an Iterator
to overcome this ConcurrentModificationException
can anyone please let me know how i should use it in a efficient manner / best practice?
Thanks in advance.
Do it as below:
public void listRemoveTest() {
stringVector.subList(0, 2).clear();
Assert.assertEquals(stringVector.size(), 3);
}