Deleting all Elements with clear - Java Collection Framework

Java examples for Collection Framework:ArrayList

Introduction

To remove all the elements, use the clear method, like this:

emps.clear();

Demo Code

import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList<Employee> emps = new ArrayList<Employee>();

    // add employees to array list
    emps.add(new Employee("A"));
    emps.add(new Employee("T"));
    emps.add(new Employee("K"));

    // print array list
    System.out.println(emps);//from w w w.  ja v a2 s  .  c  o m

    emps.clear();

    // print the array list again
    System.out.println(emps);

  }

}
class Employee{
  private String name;

  public Employee(String name) {
    this.name = name;
  }


  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
  
  @Override
  public String toString() {
    return "Employee [name=" + name + "]";
  }
  
}

Related Tutorials