Java can delete list elements. Here are some ways to delete list elements in Java.
Method 1: Use the remove() method of Iterator
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()); } }
Method 2: Use the remove() method of List, pay attention to list.size() Position
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()); } }
Method 3: Use 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()); } }
Recommended learning: Java video tutorial
The above is the detailed content of Can java delete list elements?. For more information, please follow other related articles on the PHP Chinese website!