Java ArrayList isEmpty()方法及示例
java中 ArrayList 的 isEmpty() 方法用于检查一个列表是否为空。如果列表不包含任何元素,则返回 “true”;如果列表包含任何元素,则返回 “false”。
语法
list_name.isEmpty()
参数: 它不接受任何参数。
返回: 如果list_name没有元素,返回True,否则返回False。返回的类型是布尔数据类型。
错误和异常: 该方法没有错误或异常。
在Java中演示isEmpty()的工作程序。
// Java code to demonstrate the working of
// isEmpty() method in ArrayList
// for ArrayList functions
import java.util.ArrayList;
public class GFG {
public static void main(String[] args)
{
// creating an Empty Integer ArrayList
ArrayList<Integer> arr = new ArrayList<Integer>(10);
// check if the list is empty or not using function
boolean ans = arr.isEmpty();
if (ans == true)
System.out.println("The ArrayList is empty");
else
System.out.println("The ArrayList is not empty");
// addition of a element to the ArrayList
arr.add(1);
// check if the list is empty or not
ans = arr.isEmpty();
if (ans == true)
System.out.println("The ArrayList is empty");
else
System.out.println("The ArrayList is not empty");
}
}
输出
The ArrayList is empty
The ArrayList is not empty
极客教程