The clear() method of Java AbstractCollection class

Java 8Object Oriented ProgrammingProgramming

The clear() method of the AbstractCollection class is used to remove all the elements from this collection. This makes the collection empty.

The syntax is as follows:

public void clear()

To work with AbstractCollection class in Java, import the following package:

import java.util.AbstractCollection;

First, create AbstractCollection and add some elements using the add() method:

AbstractCollection<Object> absCollection = new ArrayList<Object>();
absCollection.add("These");
absCollection.add("are");
absCollection.add("demo");
absCollection.add("elements");

Now, clear the AbstractCollection:

absCollection.clear();

The following is an example to implement AbstractCollection clear() method in Java:

Example

 Live Demo

import java.util.ArrayList;
import java.util.AbstractCollection;
public class Demo {
   public static void main(String[] args) {
      AbstractCollection<Object> absCollection = new ArrayList<Object>();
      absCollection.add("These");
      absCollection.add("are");
      absCollection.add("demo");
      absCollection.add("elements");
      System.out.println("AbstractCollection = " + absCollection);
      absCollection.clear();
      System.out.println("AbstractCollection after removing elements = " + absCollection);
   }
}

Output

AbstractCollection = [These, are, demo, elements]
AbstractCollection after removing elements = []
raja
Published on 02-Apr-2019 11:54:13
Advertisements