首页 > 代码库 > ArrayList,CopyOnWriteArrayList正确遍历方法

ArrayList,CopyOnWriteArrayList正确遍历方法

CopyOnWriteArrayList:

public static void main(String[] args) {
		final List<String> names = new CopyOnWriteArrayList<String>();
		names.add("1");
		names.add("2");
		names.add("3");
		names.add("4");
		Iterator<String> it = names.iterator();
		while (it.hasNext()) {
			if (it.next().equals("3")) {
				names.remove("3");
			}

		}
		System.out.println(names.size());
	}

ArrayList:       

public static void main(String[] args) {
	
		final List<String> names = new ArrayList<String>();
		names.add("1");
		names.add("2");
		names.add("3");
		names.add("4");
		Iterator<String> it = names.iterator();
		while (it.hasNext()) {
			if (it.next().equals("3")) {
				it.remove();
			}
		}
		System.out.println(names.size());		
	}


ArrayList,CopyOnWriteArrayList正确遍历方法