- Trending Categories
- 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
Clear an ArrayList in Java
An ArrayList can be cleared in Java using the method java.util.ArrayList.clear(). This method removes all the elements in the ArrayList. There are no parameters required by the ArrayList.clear() method and it returns no value.
A program that demonstrates this is given as follows −
Example
import java.util.ArrayList; import java.util.List; public class Demo { public static void main(String[] args) { List aList = new ArrayList(); aList.add("Orange"); aList.add("Apple"); aList.add("Peach"); aList.add("Guava"); aList.add("Mango"); System.out.println("ArrayList before using the ArrayList.clear() method: " + aList); aList.clear(); System.out.println("ArrayList after using the ArrayList.clear() method: " + aList); } }
Output
ArrayList before using the ArrayList.clear() method: [Orange, Apple, Peach, Guava, Mango] ArrayList after using the ArrayList.clear() method: []
Now let us understand the above program.
The ArrayList aList is created. Then ArrayList.add() is used to add the elements to this ArrayList. The ArrayList is displayed before and after using the ArrayList.clear() method which clears the ArrayList. A code snippet which demonstrates this is as follows −
List aList = new ArrayList(); aList.add("Orange"); aList.add("Apple"); aList.add("Peach"); aList.add("Guava"); aList.add("Mango"); System.out.println("ArrayList before using the ArrayList.clear() method: " + aList); aList.clear(); System.out.println("ArrayList after using the ArrayList.clear() method: " + aList);
Advertisements