list的removeimport java.util.*public class TestList{public static void main(String args[]){ListSt
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)); } } }
[解决办法] 在遍历的时候不能改变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();
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) { if(s.equals("5")) //这是只能是最后第二个元素的值("5") li.remove(2);//这里移除哪个元素都可以 } for (int i = 0; i < li.size(); i++) { System.out.println(li.get(i)); } } }}