Java ArrayList clear() Method with Example

In the previous article we have discussed about Java ArrayList addAll() Method with Example

In this article we are going to see the use Java ArrayList clear() method along with suitable examples,

Java ArrayList clear() Method with Example

clear():

This java.util.ArrayList.clear() method removes all the elements from an arraylist.

Syntax:

arrayListName.clear()

Where,

  • arrayListName refers to the name of your ArrayList.

Let’s see different examples to understand it more clearly.

Method-1: Java ArrayList clear() Method – Example with String Type ArrayList

Approach:

  • Create a new ArrayList of type String.
  • Add string elements into the ArrayList.
  • Display the ArrayList elements
  • Then clear all the elements from the arrayList using clear() method.
  • Print the new ArrayList.

Program:

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        // Create an ArrayList of String datatype
        ArrayList<String> arr = new ArrayList<String>();
        // Adding some elements to the ArrayList
        arr.add("Hello");
        arr.add("this");
        arr.add("is");
        arr.add("an");
        arr.add("ArrayList");
        // Prints the ArrayList elements
        System.out.println("The elements of ArrayList are: "+arr);
        // clearing all the element from the ArrayList
        arr.clear();
        // Prints the new ArrayList elements
        System.out.println("The new elements of ArrayList are: "+arr);
    }
}
Output:

The elements of ArrayList are: [Hello, this, is, an, ArrayList]
The new elements of ArrayList are: []

Method-2: Java ArrayList clear() Method – Example with Integer Type ArrayList

Approach:

  • Create a new ArrayList of type Integer.
  • Add Integer elements into the ArrayList.
  • Display the ArrayList elements
  • Then clear all the elements from the arrayList using clear() method
  • Print the new ArrayList.

Program:

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {        
        // Create a ArrayList of Integer datatype
        ArrayList<Integer> arr = new ArrayList<Integer>();
        // Adding some integer elements to the ArrayList
        arr.add(2);
        arr.add(52);
        arr.add(13);
        arr.add(17);
        arr.add(1);
        // Prints the ArrayList elements
        System.out.println("The elements of ArrayList are: "+arr);
        // clearing all the element from the ArrayList
        arr.clear();
        // Prints the new ArrayList elements
        System.out.println("The new elements of ArrayList are: "+arr);
    }
}
Output:

The elements of ArrayList are: [2, 52, 13, 17, 1]
The new elements of ArrayList are: []

Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.

Related Java Programs: