Anyway with ArrayList you can use Iterator.remove() without problem. See the example
@Before
public void setup() throws Exception {
list = new ArrayList();
int len = 100;
for (int i = 0; i < len; i++) {
list.add(i);
}
}
@Test(expected = ConcurrentModificationException.class)
public void removeWrong() throws Exception {
for (Iteratoriterator = list.iterator(); iterator.hasNext();) {
Integer i = iterator.next();
if (i >= 50) {
// wrong can throw ConcurrentModificationException
list.remove(i);
}
}
}
@Test
public void removeRight() throws Exception {
Assert.assertEquals(100, list.size());
for (Iteratoriterator = list.iterator(); iterator.hasNext();) {
Integer i = iterator.next();
if (i >= 50) {
iterator.remove();
}
}
Assert.assertEquals(50, list.size());
}
Also if you synchronize the list with List list = Collections.synchronizedList(new ArrayList(...));, it will throw a ConcurrentModificationException.
No comments:
Post a Comment