The Wayback Machine - https://web.archive.org/web/20241120052919/https://www.geeksforgeeks.org/java-program-to-empty-an-arraylist-in-java/
Open In App

Java Program to Empty an ArrayList in Java

Last Updated : 14 Dec, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

ArrayList class is a resizable array, present in ‘java.util package’. The difference between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified (i.e. if you want to append/add or remove element(s) to/from an array, you have to create a new array. However, elements can be added/appended or removed from an ArrayList without the need to create a new array.

Approaches :

  1. Using clear() method.
  2. Using removeAll() method.

Method 1: Using clear() method as the clear() method of ArrayList in Java is used to remove all the elements from an ArrayList. The ArrayList will be completely empty after this call returns.

Syntax: 

public void clear() ;

Parameters: clear function takes no parameter

Return Value: This method does not return any value.

Exception: NA

Example:

Java




// Java Program  to empty an ArrayList in Java
 
// Illustrating clear function
import java.util.ArrayList;
 
public class GFG {
 
    // Main driver method
    public static void main(String[] arg)
    {
 
        // Create an empty array list
        // with an initial capacity of 4
        ArrayList<String> numbers
            = new ArrayList<String>(4);
 
        // Use add() method to add elements
        // in numbers ArrayList
        numbers.add("10");
        numbers.add("20");
        numbers.add("30");
        numbers.add("40");
 
        // Printing numbers ArrayList
        System.out.println("Numbers ArrayList : "
                           + numbers);
 
        // Finding size of numbers ArrayList
        int numbers_size = numbers.size();
 
        // Display message
        System.out.println("Numbers ArrayList consists of: "
                           + numbers_size + " elements");
 
        // Display Message to between changes made in
        // ArrayList
 
        // System.out.println("Performing clear operation by
        // using clear function");
 
        // Using clear function
        numbers.clear();
 
        int numbers_size_new = numbers.size();
 
        // Printing new ArrayList
        System.out.println(
            "Finally Numbers ArrayList consists of: "
            + numbers_size_new + " elements");
    }
}


Output

Numbers ArrayList : [10, 20, 30, 40]
Numbers ArrayList consists of 4 elements
Performing clear operation by using clear function
Finally Numbers ArrayList consists of 0 elements

Method 2: Using removeAll() method as this method of ArrayList class is used to remove from this list all of its elements that are contained in the specified collection.

Syntax:

public boolean removeAll(Collection c) ;

Parameters: This method takes collection c as a parameter containing elements to be removed from this list.

Return Value: This method returns true if this list changed as a result of the call.

Exception/s: This method throws 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.

Example:

Java




// Java Program  to empty an ArrayList in Java
// Java code to illustrate removeAll function
 
// Importing ArrayList library
import java.util.ArrayList;
 
public class GFG {
 
    // Main driver method
    public static void main(String[] arg)
    {
 
        // Create an empty array list
        // with an initial capacity of 4
        ArrayList<String> numbers
            = new ArrayList<String>(4);
 
        // Using add() method to add elements in numbers
        // ArrayList
        numbers.add("10");
        numbers.add("20");
        numbers.add("30");
        numbers.add("40");
 
        // Printing numbers ArrayList
        System.out.println("Numbers ArrayList : "
                           + numbers);
 
        // Finding size of numbers ArrayList
        int numbers_size = numbers.size();
 
        // Display message
        System.out.println("Numbers ArrayList consists of "
                           + numbers_size + " elements");
 
        // Display Message
        System.out.println(
            "Performing clear operation by using clear function");
 
        // Using removeAll function
        numbers.removeAll(numbers);
 
        // Displaying final ArrayList count of elements
        int numbers_size_new = numbers.size();
        System.out.println(
            "Finally Numbers ArrayList consists of "
            + numbers_size_new + " elements");
    }
}


Output

Numbers ArrayList : [10, 20, 30, 40]
Numbers ArrayList consists of 4 elements
Performing clear operation by using clear function
Finally Numbers ArrayList consists of 0 elements


Previous Article
Next Article

Similar Reads

How to clone an ArrayList to another ArrayList in Java?
The clone() method of the ArrayList class is used to clone an ArrayList to another ArrayList in Java as it returns a shallow copy of its caller ArrayList. Syntax: public Object clone(); Return Value: This function returns a copy of the instance of Object. Below program illustrate the Java.util.ArrayList.clone() method: Example: Java Code // Java pr
2 min read
Copy Elements of One ArrayList to Another ArrayList in Java
It is the implementation class of List Interface. It allows duplicated objects/elements and as well as maintains the insertion order. You can get the element present inside the ArrayList by the index of it now you need to pass it into the getting (index) method. You can add the elements into ArrayList using the add() method. Syntax: ArrayList Initi
7 min read
What is the difference between ArrayList.clear() and ArrayList.removeAll()?
In Java, ArrayList.clear() and ArrayList.removeAll() are the two methods that are used to remove elements from an ArrayList, but they are used for different purposes. In this article will explain the difference between the two methods. 1. ArrayList.clear() MethodThe clear() method of ArrayList in Java is used to remove all the elements from a list.
3 min read
How to Copy and Add all List Elements to an Empty ArrayList in Java?
We can copy and add List items in Array List using addAll() method. This method accepts a Collection (Ex. List) as an argument and adds the collection items at the end of its calling Collection (Ex. ArrayList). This method returns a boolean value. addAll() return true if the collection successfully adds else it returns false. We can clone the list
2 min read
Java Program to Convert ArrayList to LinkedList
Given an array list, your task is to write a program to convert the given array list to Linked List in Java. Examples: Input: ArrayList: [Geeks, forGeeks, A computer Portal] Output: LinkedList: [Geeks, forGeeks, A computer Portal] Input: ArrayList: [1, 2, 3, 4, 5] Output: LinkedList: [1, 2, 3, 4, 5] ArrayList - An ArrayList is a part of the collect
6 min read
Java Program to Find the Length/Size of an ArrayList
Given an ArrayList in Java, the task is to write a Java program to find the length or size of the ArrayList. Examples: Input: ArrayList: [1, 2, 3, 4, 5] Output: 5 Input: ArrayList: [geeks, for, geeks] Output: 3 ArrayList - An ArrayList is a part of the collection framework and is present in java.util package. It provides us with dynamic arrays in J
2 min read
Java Program to Perform Binary Search on ArrayList
The ArrayList class is a part of the collection framework and is present in java.util package. It provides us with resizable or dynamic arrays in java. It is quite slower than standard arrays but can be helpful in some programs where we need to come up with cleaner and shorter code and lots of manipulation of an array is needed. The most effective
6 min read
Java Program to Sort ArrayList of Custom Objects By Property
Here we are going to look at the approach of sorting an ArrayList of custom objects by using a property. Approach: 1. Create a getter function which returns the value stored in the class variable. 2. Create a list and use sort() function which takes the values of the list as arguments and compares them with compareTo() method. 3. This function will
2 min read
Java Program to Sort an ArrayList
ArrayList is the class provided in the Collection framework. In Java, the collection framework is defined in java.util package. ArrayList is used to dynamically stores the elements. It is more flexible than an array because there is no size limit in ArrayList. ArrayList stores the data in an unordered manner. In some cases, we need to rearrange the
6 min read
Java Program to Search ArrayList Element Using Binary Search
Linear Search can be implemented for sorting and non-sorting elements of a Data structure particular Data structure but the average case time complexity is O(n). Whereas as Binary Search can be implemented only when the items are in sorted order and average-case time complexity is O(logn) and both Transversal have best-case Time complexity is O(1).
3 min read
Java Program to Remove an Element from ArrayList using ListIterator
ListIterator.remove() method removes the last element from the list that was returned by next() or previous() cursor positions. It can be called only once per call to next or previous. It can be made only if the operation — add(E) has not called after the last call to next or previous. Internal working in ArrayList is shown below be its removal or
4 min read
Java Program to Traverse Through ArrayList in Reverse Direction
ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java just as Vector in C++. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. The task is to insert an element in ArrayList and then Reverse it or say re
4 min read
Java Program to Add an Element to ArrayList using ListIterator
In this article, we will learn how to add an element to ArrayList using ListIterator. The ListIterator is used to return a list iterator over the list elements. The listIterator() returns an iterator over the list from the beginning, but the listIterator(index) returns an iterator over the list from the given index. Syntax: // listIterator() method
2 min read
Java Program to Copy Elements of ArrayList to Vector
Vector implements List Interface, like ArrayList it also maintains insertion order but it is rarely used in the non-thread environment as it is synchronized, and due to which it gives a poor performance in adding, searching, deleting, and updating of its elements. To copy elements from one collection to others, pass the object of ArrayList to the c
4 min read
Java Program to Implement ArrayList API
ArrayList is a resizable-array of the list interface. It provides the methods that can be used to manipulate the size of the array whenever required. Each instance of an ArrayList has some capacity, the capacity means the size to store the elements in the ArrayList. If you do not assign any capacity then the default capacity is 10, but if you enter
5 min read
Java Program to Sort Objects in ArrayList by Date
The foremost tool that strikes is the sort() method to be used for the comparator mechanism of the Collections class which sorts in the decreasing order. Yes if in generic we want to achieve the goal considering the boundary condition where objects to sorted are user-defined then blindly do with Comparator. Both approaches are discussed below where
6 min read
Java Program to Create ArrayList From Enumeration
Enumerations serve the purpose of representing a group of named constants in a programming language. Enums are used when we know all possible values at compile-time, such as choices on a menu, rounding modes, command-line flags, etc. It is not necessary that the set of constants in an enum type stay fixed for all time. Steps To create an ArrayList
2 min read
Java.util.ArrayList.add() Method in Java
Below are the add() methods of ArrayList in Java: boolean add(Object o) : This method appends the specified element to the end of this list. Parameters: object o: The element to be appended to this list. Exception: NA // Java code to illustrate add(Object o) import java.io.*; import java.util.ArrayList; public class ArrayListDemo { public static vo
2 min read
Java.util.ArrayList.addall() method in Java
Below are the addAll() methods of ArrayList in Java: boolean addAll(Collection c) : This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator. The behavior of this operation is undefined if the specified collection is modified while the ope
4 min read
Java.util.Arraylist.indexOf() in Java
The indexOf() method of ArrayList returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. Syntax : public int IndexOf(Object o) obj : The element to search for. // Java code to demonstrate the working of // indexOf in ArrayList // for ArrayList functions import java.util.Arra
2 min read
ArrayList vs LinkedList in Java
An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. However, the limitation of the array is that the size of the array is predefined and fixed. There are multiple ways to solve this problem. In this article, the difference between two classes that are implemented to
5 min read
Arraylist removeRange() in Java with examples
The removeRange() method of ArrayList in Java is used to remove all elements within the specified range from an ArrayList object. It shifts any succeeding elements to the left. This call shortens the list by (toIndex-fromIndex) elements where toIndex is the ending index and fromIndex is the starting index within which all elements are to be removed
3 min read
ArrayList get(index) Method in Java with Examples
The get() method of ArrayList in Java is used to get the element of a specified index within the list. Syntax: get(index) Parameter: Index of the elements to be returned. It is of data-type int. Return Type: The element at the specified index in the given list. Exception: It throws IndexOutOfBoundsException if the index is out of range (index=size(
2 min read
Arraylist lastIndexOf() in Java with example
The lastIndexOf() method of ArrayList in Java is used to get the index of the last occurrence of an element in an ArrayList object. Syntax : lastIndexOf(element) Parameter : The element whose last index is to be returned. Returns : It returns the last occurrence of the element passed in the parameter. It returns -1 if the element is not found. Prog
2 min read
Arraylist.contains() in Java
In Java, ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Syntax of Java ArrayList contains() :public boolean contains(Object) object-element to be searched for Parameters: object- element whose presence in this list is to be tested Returns: It returns true if the specified element i
2 min read
ArrayList trimToSize() in Java with example
The trimToSize() method of ArrayList in Java trims the capacity of an ArrayList instance to be the list's current size. This method is used to trim an ArrayList instance to the number of elements it contains. Syntax: trimToSize() Parameter: It does not accepts any parameter. Return Value: It does not returns any value. It trims the capacity of this
1 min read
ArrayList isEmpty() in Java with example
The isEmpty() method of ArrayList in java is used to check if a list is empty or not. It returns true if the list contains no elements otherwise it returns false if the list contains any element. Syntax: list_name.isEmpty() Parameter: It does not accepts any parameter. Returns: It returns True if the list list_name has no elements else it returns f
2 min read
ArrayList clear() Method in Java with Examples
The clear() method of ArrayList in Java is used to remove all the elements from a list. The list will be empty after this call returns so whenever this operation has been performed all elements of the corresponding ArrayList will be deleted so it does it becomes an essential function for deleting elements in ArrayList from memory leading to optimiz
2 min read
Convert HashSet to a ArrayList in Java
ArrayList class is a resizable array, present in java.util package. The difference between an array and an ArrayList in Java, is that the size of an array cannot be modified (i.e. if you want to append/add or remove element(s) to/from an array, you have to create a new array. However, elements can be added/appended or removed from an ArrayList with
4 min read
ArrayList retainAll() method in Java
The retainAll() method of ArrayList is used to remove all the array list's elements that are not contained in the specified collection or retains all matching elements in the current ArrayList instance that match all elements from the Collection list passed as a parameter to the method. Syntax: public boolean retainAll(Collection C) Parameters: The
4 min read
Practice Tags :
three90RightbarBannerImg