日期:2014-05-20  浏览次数:20729 次

list的remove

import java.util.*;

public class TestList{
  public static void main(String args[]){
  List<String> li = new ArrayList<String>();    
    li.add("1");    
    li.add("2");    
    li.add("3");    
    li.add("4");    
    li.add("5");    
    li.add("6"); 
    for (String s : li) {    
        li.remove(s);    
    }
for (int i = 0; i < li.size(); i++) {    
System.out.println(li.get(i));    
}
    } 
}


用增强的for循环,为什么会抛出ConcurrentModificationException的异常?

------解决方案--------------------
增强的for循环里面不能调remove()

如果要在loop里面remove:
for(Iterator<String> it=li.iterator();it.hasNext();){
   it.next();
   it.remove();
}


------解决方案--------------------
在遍历的时候不能改变ArrayList,在遍历的时候进行修改就会报这个错
http://download.oracle.com/javase/1.5.0/docs/api/java/util/ConcurrentModificationException.html
上面是java-doc上的说明
------解决方案--------------------
太久没用java,忘记了,但是下面这段应该可以回答楼主的问题了:
The remove method removes the last element that was returned by next from the underlying Collection. The remove method may be called only once per call to next and throws an exception if this rule is violated.

Note that Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.

Use Iterator instead of the for-each construct when you need to:

    * Remove the current element. The for-each construct hides the iterator, so you cannot call remove. Therefore, the for-each construct is not usable for filtering.
    * Iterate over multiple collections in parallel. 

The following method shows you how to use an Iterator to filter an arbitrary Collection — that is, traverse the collection removing specific elements.

    static void filter(Collection<?> c) {
        for (Iterator<?> it = c.iterator(); it.hasNext(); )
            if (!cond(it.next()))
                it.remove();