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

Can java delete list elements?

青灯夜游
Release: 2019-12-31 10:54:12
Original
2283 people have browsed it

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());
    }
}
Copy after login

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());
    }
}
Copy after login

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());
    }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template