How do I empty a list in Java?


Solution

We can clear a list easily using its clear() method.

Syntax

void clear()

Removes all the elements of the list.

Throws

  • UnsupportedOperationException − If the clear operation is not supported by this list

Example

The following example shows how to clear elements from the list using the clear() method.

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.List;

public class CollectionsDemo {
   public static void main(String[] args) {
      // Create a list object
      List<Integer> list = new ArrayList<>();

      // add elements to the list
      list.add(1);
      list.add(2);
      list.add(3);
      list.add(4);
      list.add(5);
      list.add(6);

      // print the list
      System.out.println(list);

      list.clear();
      System.out.println(list);
   }
}

Output

This will produce the following result −

[1, 2, 3, 4, 5, 6]
[]

Updated on: 09-May-2022

636 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements