A collection with the function, print one then remove one. how to implement?

1355 단어
a collection with the function, print one then remove one. how to implement?
first is a fault demon.
public class Test {
	public static void main(String[] args){
		ArrayList<String> col = new ArrayList<String>();
		col.add("line 1");
		col.add("line 2");
		col.add("line 3");
		
		for(int i=0;i<col.size();i++){
			System.out.println(col.get(i));
			col.remove(i);
		}
	}
}
line 1
line 3

try second time
		for(String var : col){
			System.out.println(var);
			col.remove(var);
		}
line 1
Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:819)
	at java.util.ArrayList$Itr.next(ArrayList.java:791)
	at Test.main(Test.java:14)

third time
		for(int i=col.size()-1;i>=0;i=col.size()-1){
			System.out.println(col.get(i));
			col.remove(i);
		}
line 3
line 2
line 1

seems good.
		for(int i=0;i<col.size();i=0){
			System.out.println(col.get(i));
			col.remove(i);
		}
line 1
line 2
line 3

also worked.

좋은 웹페이지 즐겨찾기