
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do I empty a list in Java?
List Interface is a collection in Java that is used for storing elements in a sequence. It also allows us to save duplicates as well as null values.
In this article, we will learn how to empty a list in Java. Following are the ways to empty a list in Java:
Using clear() Method
The clear() method of the List interface is used to remove all elements from the list. It removes all the elements but returns nothing. Following is the syntax of the clear() method.
list.clear();
Example
In the following example, we will create a list of integers and then use the clear() method to empty the list.
import java.util.ArrayList; import java.util.List; public class EmptyList { public static void main(String[] args) { List<Integer> numbers = new ArrayList<>(); numbers.add(1); numbers.add(2); numbers.add(3); System.out.println("List before clearing: " + numbers); numbers.clear(); System.out.println("List after clearing: " + numbers); } }
Following is the output of the above code:
List before clearing: [1, 2, 3] List after clearing: []
Using removeAll() Method
The removeAll()method is used for removing all elements of another collection from the list. It takes a collection as an argument and removes all the elements of that collection from the list. We will pass the same list as an argument to remove all its elements.
Syntax
Following is the syntax of the removeAll() method. We will pass the same list as an argument to remove all its elements.
list.removeAll(list);
Example
In the following example, we will create a list, we will remove all elements of a certain collection from the list, and we will pass the same list as an argument to remove all its elements.
import java.util.ArrayList; import java.util.List; public class EmptyList { public static void main(String[] args) { List<Integer> numbers = new ArrayList<>(); numbers.add(1); numbers.add(2); numbers.add(3); System.out.println("List before removing all elements: " + numbers); numbers.removeAll(numbers); System.out.println("List after removing all elements: " + numbers); } }
Following is the output of the above code:
List before removing all elements: [1, 2, 3] List after removing all elements: []