Java 删除List元素的正确方式
方式一:使用Iterator的remove()方法
public class Test { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("aa"); list.add("bb"); list.add("cc"); Iterator<String> it = list.iterator(); while(it.hasNext()){ String str = (String)it.next(); if("aa".equals(str)){ it.remove(); } } System.out.println(list.size()); } }
方式二:使用List的remove()方法,注意list.size()的位置
public class Test { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("aa"); list.add("bb"); list.add("cc"); for (int i = list.size() - 1; i >= 0; i--) { String str = list.get(i); if ("aa".equals(str)) { list.remove(str); } } System.out.println(list.size()); } }
方式三:使用CopyOnWriteArrayList
public class Test { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("aa"); list.add("bb"); list.add("cc"); CopyOnWriteArrayList<String> cowList = new CopyOnWriteArrayList<String>(list); for (String str : cowList) { if ("aa".equals(str)) { cowList.remove(str); } } System.out.println(cowList.size()); } }