Java ArrayList clear() Method Example

The clear() method of java.util.ArrayList class will remove all the content of the ArrayList

Signature

public void clear()

This method removes all of the elements from this list. The list will be empty after this call returns.

Example

The following example shows the usage of ArrayList.clear() method.

import java.util.ArrayList;

public class ClearMethodArrayListExample {
	public static void main(String args[])
	{
		// create an empty ArrayList
		ArrayList<String> l = new ArrayList<String>();
		
		// use add() method to add elements to the ArrayList
		l.add("Element1");
		l.add("Element2");
		l.add("Element3");

		System.out.println("Size of the List before clear -- "+l.size());
		
		//Printing the elements of the ArrayList
		System.out.println("Elements of the list before clear");

		for(String temp:l)
		{
			System.out.println(temp);
		}
		
		//Removing the all the contents of the ArrayList 
		l.clear();
		
		System.out.println("Size of the List After clear -- "+l.size());
		
		//Printing the elements of the ArrayList
		System.out.println("Elements of the list after clear");
		for(String temp:l)
		{
			System.out.println(temp);
		}
	}
}

Output

Size of the List before clear -- 3
Elements of the list before clear
Element1
Element2
Element3
Size of the List After clear -- 0
Elements of the list after clear

Leave a Reply

Your email address will not be published. Required fields are marked *