在Java中使用示例列出List isEmpty()方法

在Java中使用示例列出List isEmpty()方法

在Java中,List接口的 isEmpty() 方法用于检查一个列表是否为空。如果列表不包含任何元素,则返回true,否则返回false。

语法:

boolean isEmpty()

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

返回值: 如果列表没有元素,则返回True,否则返回false。返回类型是布尔类型。

错误和异常: 此方法没有错误或异常。

Java程序示例演示了isEmpty()的工作方式:

// Java code to demonstrate the working of
// isEmpty() method in List interface
import java.util.*;

public class GFG {
    public static void main(String[] args)
    {
        // creating an Empty Integer List
        List<Integer> arr = new ArrayList<Integer>(10);

        // check if the list is empty or not
        // using isEmpty() function
        boolean ans = arr.isEmpty();
        if (ans == true)
            System.out.println("The List is empty");
        else
            System.out.println("The List is not empty");

        // addition of a element to
        // the List
        arr.add(1);

        // check if the list is empty or not
        // after adding an element
        ans = arr.isEmpty();
        if (ans == true)
            System.out.println("The List is empty");
        else
            System.out.println("The List is not empty");
    }
}

输出:

The List is empty
The List is not empty

参考文献: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#isEmpty()

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程