Java ArrayList.clear() Method

 Posted On  | Yashwant Chavan 

In this tutorial you will learn about Java ArrayList clear() method. clear() method removes all of the elements from this list.


void java.util.ArrayList.clear() 

Removes all of the elements from this list. The list will be empty after calling clear() method.

Java ArrayList clear() example

Refer below steps

  • Constructs an empty list with an initial capacity using new ArrayList<String>().
  • Add some elements in the ArrayList using add() method.
  • Print the size of ArrayList before calling clear() method. It returns 3.
  • Clear the ArrayList using colors.clear(). It removes all the elements from the List.
  • Print the size of ArrayList after calling clear() method. It return 0.

import java.util.ArrayList;

public class ArrayListClear {
    public static void main(String[] args) {

        ArrayList <String> colors = new ArrayList <String> ();
        System.out.println("List size before clear() :- " + colors.size());
        System.out.println("List size after clear() :- " + colors.size());



List size before clear() :- 3
List size after clear() :- 0

© 2018

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0282 seconds.