
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
Remove All Elements of ArrayList in Java
The List interface extends Collection interface and stores a sequence of elements. The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list. Unlike sets, list allows duplicate elements, allows multiple null values if null value is allowed in the list. List provides add, remove methods to add/remove elements. In order to clear a list or remove all the elements from the list, we can use clear() method of the List. We can also use removeAll() method as well to achive the same effect as clear() method.
In this article, we're going to cover clear() and removeAll() methods with corresponding examples.
Syntax - clear() method
void clear()
Notes
Removes all of the elements from this list.
The list will be empty after this call returns.
Throws
UnsupportedOperationException - If the clear operation is not supported by this list.
Syntax - removeAll() method
boolean removeAll(Collection<?> c)
Removes from this list all of its elements that are contained in the specified collection.
Parameters
c - collection containing elements to be removed from this list.
Returns
True if this list changed as a result of the call
Throws
UnsupportedOperationException - If the removeAll operation is not supported by this list.
ClassCastException - If the class of an element of this list is incompatible with the specified collection (optional).
NullPointerException - If this list contains a null element and the specified collection does not permit null elements (optional), or if the specified collection is null.
Example 1
Following is the example showing the usage of clear() method −
package com.tutorialspoint; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CollectionsDemo { public static void main(String[] args) { List<Integer> list = new ArrayList<>(Arrays.asList(0,1,2,3,4,5,6,7,8,9)); System.out.println("List: " + list); list.clear(); System.out.println("Cleared List: " + list); } }
Output
This will produce the following result −
List: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Cleared List: []
Example 2
Following is the example showing the usage of removeAll() method −
package com.tutorialspoint; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CollectionsDemo { public static void main(String[] args) { List<Integer> list = new ArrayList<>(Arrays.asList(0,1,2,3,4,5,6,7,8,9)); System.out.println("List: " + list); list.removeAll(list); System.out.println("Cleared List: " + list); } }
Output
This will produce the following result −
List: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Cleared List: []