Remove All Element From Arraylist Example

In this Tutorial we will learn how to remove all elements from arraylist java  or how to clear arraylist . We have these method to make clean or empty ararylist

  1. ArrayList.clear() Method.
  2. ArrayList().removeAll Method

1. ArrayList.clear() Method

Syntax:

public void clear() {

}

This method  removes all of the elements from this list. The list will be empty after this call returns.

import java.util.ArrayList;

public class RemoveAll {

public static void main(String[] args) {

ArrayList<String> arr = new ArrayList<String>();

// add element in arraylist
arr.add("c");
arr.add("c");
arr.add("php");
arr.add("html");
arr.add("java");

// print arraylist
System.out.println("arrayList is = " + arr);

/*
* Removes all of the elements from this list.
*/
arr.clear();

System.out.println("After Clear arrayList is="+arr);
}

}

Output:

arrayList is = [c, c, php, html, java]

After Clear arrayList is=[]

2. ArrayList().removeAll Method

Syntax :

public boolean removeAll(Collection<?> c) {

}
  • This method removes from this list all of its elements that are contained in the given collection.
  • It take collection c as paramater , which containing elements to be removed from this list
  • It returns true if this list changed as a result of the call
  • It throws ClassCastException – if the class of an element of this list is incompatible with the specified collection (optional)
    NullPointerException – if this list contains a null element and the specified collection does not permit null elements (optional), or if the specified collection is null
import java.util.ArrayList;

public class RemoveAll2 {

public static void main(String[] args) {
ArrayList<String> arr = new ArrayList<String>();
// add element in arraylist
arr.add("c");
arr.add("php");
arr.add("html");
arr.add("java");
// print arraylist
System.out.println("Before Removing arrayList is = " + arr);

arr.removeAll(arr);
System.out.println("After Remove all element of aarraylist is="+arr);

}

}

Output:

Before Removing arrayList is = [c, php, html, java]

After Remove all element of aarraylist is=[]

 

Leave a Reply

Your email address will not be published. Required fields are marked *

9 + 1 =