Home » Java programming language

Java ArrayList clear() Method with Example

ArrayList Class clear() method: Here, we are going to learn about the clear() method of ArrayList Class with its syntax and example.
Submitted by Preeti Jain, on January 18, 2020

ArrayList Class clear() method

  • clear() method is available in java.util package.
  • clear() method is used to delete or clear all the elements from this Arraylist.
  • clear() method is a non-static method so it is accessible with the class object and if we try to access the method with the class name then we will get an error.
  • clear() method does not throw an exception at the time of clearing Arraylist.

Syntax:

    public void clear();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of the method is void, it returns nothing.

Example:

// Java program to demonstrate the example 
// of void clear() method of ArrayList.

import java.util.*;

public class ClearOfArrayList {
    public static void main(String[] args) {
        // Create an ArrayList with initial 
        // capacity of storing elements

        ArrayList < String > arr_l = new ArrayList < String > (10);

        // By using add() method is to add 
        // elements in this ArrayList
        arr_l.add("C");
        arr_l.add("C++");
        arr_l.add("JAVA");
        arr_l.add("DOTNET");
        arr_l.add("PHP");
        arr_l.add("JAVA");

        // Display ArrayList 
        System.out.println("ArrayList Elements :" + arr_l);

        // By using clear() method is to
        // remove all the elements from the ArrayList
        arr_l.clear();

        // Display ArrayList 
        System.out.println("arr_l.clear() : " + arr_l);
    }
}

Output

ArrayList Elements :[C, C++, JAVA, DOTNET, PHP, JAVA]
arr_l.clear() : []


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.