Java ArrayList.clear()

 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.

syntax

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.
package com.technicalkeeda.app;

import java.util.ArrayList;

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

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

    }
}

Output

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


Promote your Blog, Website, or services on technicalkeeda.com, My paypal id: yashwantchavan@gmail.com

Payment will be accepted through paypal only.


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0234 seconds.