📅  最后修改于: 2023-12-03 14:42:12.925000             🧑  作者: Mango
In Java, the ArrayList
class is a commonly used implementation of the List
interface, which provides a dynamic array-like data structure. The isEmpty()
method is a member of this class that returns a boolean value indicating whether the ArrayList
is empty or not. This method is quite useful when you want to check if the list contains any elements before performing further operations.
The syntax for isEmpty()
method is:
public boolean isEmpty()
The isEmpty()
method returns a boolean value:
true
if the ArrayList
is empty and contains no elements.false
if the ArrayList
contains one or more elements.Here is an example that demonstrates the usage of isEmpty()
method:
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
System.out.println("Is the ArrayList empty? " + fruits.isEmpty()); // Output: Is the ArrayList empty? true
fruits.add("Apple");
fruits.add("Banana");
System.out.println("Is the ArrayList empty? " + fruits.isEmpty()); // Output: Is the ArrayList empty? false
}
}
In this example, we first create an empty ArrayList
called fruits
. We then use the isEmpty()
method to check if the list is empty and print the result. As expected, the output is true
. After adding two elements to the ArrayList
, we again use the isEmpty()
method to check if the list is empty. This time, the output is false
.
The isEmpty()
method of the ArrayList
class in Java is a convenient way to check if the list is empty or not. By using this method, you can avoid potential errors when trying to access or manipulate elements in an empty list.