Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the ArrayList.isEmpty() method in Java?

Kainat Asif

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The ArrayList.isEmpty() method in Java is used to check if a list is empty. An empty list means that it contains no elements.

Syntax

The ArrayList.isEmpty() method can be declared as shown in the code below:

public boolean isEmpty()

Return value

The ArrayList.isEmpty() method returns a boolean such that:

  • The return value is true if the list is empty.
  • The return value is false if the list is not empty.

Example

Consider the code below, which demonstrates the use of the ArrayList.isEmpty() method:

import java.util.ArrayList;
public class Example1 {
public static void main(String[] args)
{
ArrayList<Integer> list1 = new ArrayList<Integer>(5);
boolean empty = list1.isEmpty();
System.out.println("list1 is empty: " + empty);
list1.add(1);
list1.add(2);
list1.add(3);
empty = list1.isEmpty();
System.out.println("list1 is empty: " + empty);
}
}

Explanation

  • A list list1 is declared in line 6.
  • The ArrayList.isEmpty() method is used in line 8 to check if list1 is empty. The ArrayList.isEmpty() returns true because list1 contains no elements.
  • Three elements are added in list1 in lines 11-13 using the add() method.
  • The ArrayList.isEmpty() method is used in line 15 to check if list1 is empty. The ArrayList.isEmpty() returns false because list1 now contains three elements.

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring