java中迴圈遍歷刪除List和Set集合中元素的方
阿新 • • 發佈:2018-12-15
1.異常java一邊遍歷一邊刪除集合中的元素會報異常ConcurrentModificationException
2.正確的做法如下:
package list; import java.util.*; public class Demo { public static void main(String[] args) { List<Object> obj = new ArrayList<Object>(); obj.add("a"); obj.add("b"); obj.add("c"); System.out.println("移除前:" + obj.toString()); Iterator<Object> it = obj.iterator(); for(int i=0; i<obj.size(); i++){ System.out.println(i); Object name = it.next(); if("a".equals(name) || "b".equals(name)){ it.remove(); i--; } } System.out.println("移除後: " + obj.toString()); } }
package set; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class Demo { public static void main(String[] args) { Set<Object> obj = new HashSet<Object>(); obj.add("a"); obj.add("b"); obj.add("c"); System.out.println("移除前:" + obj.toString()); Iterator<Object> it = obj.iterator(); for(int i=0; i<obj.size(); i++){ System.out.println(i); Object name = it.next(); if("a".equals(name) || "b".equals(name)){ it.remove(); i--; } } System.out.println("移除後: " + obj.toString()); } }
//遍歷map的方法:
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
原文地址:http://www.cnblogs.com/-liuhuanchao/p/4149806.html(侵刪)
結尾:java8的新streamApi更方便,然而專案中用的是java7-