- 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);
- Related Articles
- Clone an ArrayList in Java
- Initialize an ArrayList in Java
- Java Program to Empty an ArrayList in Java
- Sort Elements in an ArrayList in Java
- Search an element of ArrayList in Java
- How to reverse an ArrayList in Java?
- How to synchronize an ArrayList in Java?
- Convert an ArrayList to HashSet in Java
- Retrieve an element from ArrayList in Java
- Loop through an ArrayList using an Iterator in Java
- Get the size of an ArrayList in Java
- Check existence of an element in Java ArrayList
- Remove duplicate items from an ArrayList in Java
- How to create an ArrayList from an Array in Java?
- How to replace an element of an ArrayList in Java?

Advertisements