Low Orbit Flux Logo 2 D

Java How To Empty An Arraylist

It is easy to empty an Arraylist in Java.

To empty an ArrayList in Java use either of the following methods:


list1.clear();
list1.removeAll(list1);

The clear method is much faster.

Here is an example using both:


import java.util.ArrayList;
  
public class Test1 {

        public static void main( String[] args ){
                ArrayList list1 = new ArrayList();
                list1.add("abc");
                list1.add("def");

                ArrayList list2 = new ArrayList();
                list2.add("ghi");
                list2.add("jkl");

                System.out.println(list1);
                System.out.println(list2);

                list1.clear();
                list2.removeAll(list2);

                System.out.println(list1);
                System.out.println(list2);
        }
}
</code></pre>