- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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?
Solution
We can clear a list easily using its clear() method.
Syntax
void clear()
Removes all the elements of the list.
Throws
UnsupportedOperationException − If the clear operation is not supported by this list
Example
The following example shows how to clear elements from the list using the clear() method.
package com.tutorialspoint; import java.util.ArrayList; import java.util.List; public class CollectionsDemo { public static void main(String[] args) { // Create a list object List<Integer> list = new ArrayList<>(); // add elements to the list list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); list.add(6); // print the list System.out.println(list); list.clear(); System.out.println(list); } }
Output
This will produce the following result −
[1, 2, 3, 4, 5, 6] []
Advertisements