Home  >  Article  >  Java  >  Can java delete list elements?

Can java delete list elements?

青灯夜游
青灯夜游Original
2019-12-31 10:54:122264browse

Can java delete list elements?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn