Skip to content

Instantly share code, notes, and snippets.

@ts-3156
Created March 24, 2011 09:26
Show Gist options
  • Save ts-3156/884789 to your computer and use it in GitHub Desktop.
Save ts-3156/884789 to your computer and use it in GitHub Desktop.
package test;
import java.util.ArrayList;
public class Test {
public Test() {
ok();
bad();
}
private void ok(){
ArrayList<String> numbers = initialize(10);
for(int i = 0; i < numbers.size(); i++){
if(i == 5)
numbers.remove(i);
if(i == 9){
// 呼ばれません。つまり、変化したsize()の値によって、ループの回数が1回減ってます
System.out.println(i + "です");
}
}
System.out.println(numbers.size());// 9が出力されます
}
private void bad(){
ArrayList<String> numbers = initialize(10);
int i = 0;
for(String number: numbers){ // ← ここでConcurrentModificationException
if(i == 5)
numbers.remove(i);
i++;
}
}
private ArrayList<String> initialize(int num){
ArrayList<String> numbers = new ArrayList<String>(num);
for(int i = 0; i < num; i++)
numbers.add("" + i);
return numbers;
}
public static void main(String[] args) {
new Test();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment