Sunday, 10 May 2015

Remove All Element From Arraylist Example

 Remove All Element From Arraylist Example

Method 1:

We can remove all element of arraylist using clear() method . clear() removes all element from the list and return empty list.

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=[]

Method 2:


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=[]



Related Posts: 

 


Storing Java Object In ArrayList




1 comment: