Java中的List clear()方法及其示例

Java中的List clear()方法及其示例

在Java中,List接口的 clear() 方法用于从List容器中删除所有元素。该方法不会删除List容器,而只是删除其中的所有元素。 语法:

public void clear()

参数: 该方法不接受任何参数。

返回值: 该函数的返回类型为void,不返回任何内容。

异常: 如果该列表不支持clear()操作,则该方法会抛出 UnsupportedOperationException 异常。以下程序说明了List.clear()方法:

程序1:

// Java code to illustrate clear() method
import java.io.*;
import java.util.*;

public class ListDemo {
    public static void main(String[] args)
    {

        // create an empty list with an initial capacity
        List<String> list = new ArrayList<String>(5);

        // use add() method to initially
        // add elements in the list
        list.add("Geeks");
        list.add("For");
        list.add("Geeks");

        // Remove all elements from the List
        list.clear();

        // print the List
        System.out.println(list);
    }
}

输出:

[]

程序2:

// Java code to illustrate clear() method
import java.io.*;
import java.util.*;

public class ListDemo {
    public static void main(String[] args)
    {

        // create an empty list with an initial capacity
        List<Integer> list = new ArrayList<Integer>(5);

        // use add() method to initially
        // add elements in the list
        list.add(10);
        list.add(20);
        list.add(30);

        // clear the list
        list.clear();

        // prints all the elements available in list
        System.out.println(list);
    }
}

输出:

[]

参考链接: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#clear()

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程