Java List isEmpty()方法及示例
java中List接口的 isEmpty() 方法用于检查一个列表是否为空。如果列表不包含任何元素,则返回 “真”;如果列表包含任何元素,则返回 “假”。
语法
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()