- ArrayList clear() Method – How to Empty or clear ArrayList in Java
- 1. ArrayList clear() method Syntax
- How to empty and ArrayList in Java?
- 1. ArrayList clear() method Example
- 2. ArrayList.clear() or Create a New List?
- 3. ArrayList.clean() vs ArrayList.removeAll()
- Summary
- Clear an Array in Java
- Clear an Array Using the for Loop in Java
- Clear an Array Using the fill() Method in Java
- Clear an Array by Setting a Null Reference in Java
- Clear an Array via Assigning a New Array Reference in Java
- Related Article — Java Array
- Clear ArrayList with clear() vs. removeAll()
ArrayList clear() Method – How to Empty or clear ArrayList in Java
1. ArrayList clear() method Syntax
Before we look in to more details, let’s look at the clear() method syntax from the ArrayList.The ArrayList clear() method will iterate through each element of the list and just sets the array elements to null .
If we just want to clear the ArrayList, clear() method will much faster as it only set the reference to each element as null doing no additional data manipulation.
How to empty and ArrayList in Java?
We can use ArrayList.clear() or ArrayList.removeAll() method to empty an ArrayList. The clear() method is the fastest as it only set the reference to the underlying array as null while the removeAll() will perform some additional work.
1. ArrayList clear() method Example
Here is a complete example to clear all the elements from an ArrayList.
package com.javadevjournal; import java.util.ArrayList; import java.util.List; public class ArraylistClearExample < public static void main(String[] args) < List < String >list = new ArrayList < >(); list.add("Sunday"); list.add("Monday"); list.add("Tuesday"); list.add("Wednesday"); list.add("Thursday"); list.add("Friday"); list.add("Saturday"); System.out.println(list); //clear the list list.clear(); System.out.println(list); > >
[Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday] []
When performing ArrayList.clear() it only removes references to array elements and sets size to 0 , however, capacity stays as it was.
2. ArrayList.clear() or Create a New List?
When working on the ArrayList clear() method, there is a natural question “Should we use clear() method or create a new list using new ArrayList() ?”. There are multiple reason we should prefer to use clear() method over new list.
- Most times we might not be allowed to reassign a reference field that points to an ArrayList.
- The variable might be declared as List. The actual type could be LinkedList and you want to preserve it instead of replacing the implementation with an ArrayList.
class App < // Can clear() but not reassign final List < String >list = new ArrayList < >(); >
Keep in mind that it might be faster if the ArrayList will be cleared and refilled thousand times repeatedly as the clear() method will only clear the elements from the list but won’t change the size of backing array, this can definitely help us avoid dynamic resizing of the ArrayList.
3. ArrayList.clean() vs ArrayList.removeAll()
Both ArrayList.clear() and ArrayList.removeAll() empty an ArrayList, however they clear the list differently. Let’s look at the difference between the ArrayList.clear() vs ArrayList.removeAll().
- The clear() method clear the list by assigning the null value to each element. It does not change the underlying backing Array.
- In removeAll() method, it first check if the element is present using the contains() method, it removes the element in case the item is present. The removeAll() perform some additional steps before removing an element from the underlying list.
public boolean removeAll(Collection c) < Objects.requireNonNull(c); boolean modified = false; Iterator it = iterator(); while (it.hasNext()) < if (c.contains(it.next())) < it.remove(); modified = true; >> return modified; >
From ArrayList
public boolean removeAll(Collection c) < return batchRemove(c, false, 0, size); >boolean batchRemove(Collection c, boolean complement, final int from, final int end) < Objects.requireNonNull(c); final Object[] es = elementData; int r; // Optimize for initial run of survivors for (r = from;; r++) < if (r == end) return false; if (c.contains(es[r]) != complement) break; >int w = r++; try < for (Object e; r < end; r++) if (c.contains(e = es[r]) == complement) es[w++] = e; >catch (Throwable ex) < // Preserve behavioral compatibility with AbstractCollection, // even if c.contains() throws. System.arraycopy(es, r, es, w, end - r); w += end - r; throw ex; >finally < modCount += end - w; shiftTailOverGap(es, w, end); >return true; >
Let’s look at some of the extra points while using these options:
- The clear() method on avg is much faster since it doesn’t have to deal with all those extra method calls as used in the removeAll() method.
- The c.contains() increase the time complexity of removeAll() method. ( O(n) vs O(n2) )
Summary
In this article, we look at the ArrayList clear() method. We saw when we should use the clear() method as compare to creating and assigning a new ArrayList. At the end of this article, we look at the difference between the ArrayList clear() vs removeAll() method. The source code for these articles is available on our GitHub repository.
Clear an Array in Java
- Clear an Array Using the for Loop in Java
- Clear an Array Using the fill() Method in Java
- Clear an Array by Setting a Null Reference in Java
- Clear an Array via Assigning a New Array Reference in Java
This tutorial introduces how to empty or clear an array in Java. We’ll cite some example codes to help you understand this topic further.
To Clear an array, we can use several ways. For example, we can set a null value to each array index or set null to the array reference only. You can also use the fill() method of the Arrays class to set default values to the array. Let’s see some examples below.
Clear an Array Using the for Loop in Java
This is a simple example of using a for-loop to fill a default value to each index of the array. This is a basic approach, but it requires one extra for-loop that may lead to program complexity. See the example here:
public class SimpleTesting public static void main(String[] args) int[] arr = 2,22,56,78,14>; for (int i : arr) System.out.println(i); > // Setting default value to empty array for (int i = 0; i arr.length; i++) arr[i] = 0; > for (int i : arr) System.out.println(i); > > >
Clear an Array Using the fill() Method in Java
This method is another solution where we used the fill() method of the Arrays class to clear an array by setting a new value. After using the fill() method, we used the for-loop to access its elements and see if all the parts have cleared.
import java.util.Arrays; public class SimpleTesting public static void main(String[] args) int[] arr = 2,22,56,78,14>; for (int i : arr) System.out.println(i); > // Setting default value to empty array System.out.println("After Clearing Array:"); Arrays.fill(arr, 0); for (int i : arr) System.out.println(i); > > >
2 22 56 78 14 After Clearing Array: 0 0 0 0 0
Clear an Array by Setting a Null Reference in Java
If you want to make an array entirely empty (i.e., no element, even no default elements), you can assign a null reference to the array object. After making an array null, don’t try to access its elements, or else the compiler will return the NullPointerException command. Check the example code below:
public class SimpleTesting public static void main(String[] args) int[] arr = 2,22,56,78,14>; for (int i : arr) System.out.println(i); > // Setting null value to empty array arr = null; for (int i : arr) System.out.println(i); > > >
2 22 56 78 14 Exception in thread "main" java.lang.NullPointerException at myjavaproject.SimpleTesting.main(SimpleTesting.java:11)
Clear an Array via Assigning a New Array Reference in Java
We can clear an array by creating a new empty one and assigning the reference of a new array to it. This method is a little tricky; however, it’s useful to try it and check if it doesn’t throw any exception, since the new array has its default values. Refer to the sample below:
public class SimpleTesting public static void main(String[] args) int[] arr = 2,22,56,78,14>; for (int i : arr) System.out.println(i); > // Setting new empty array System.out.println("After clearing Array:"); arr = new int[arr.length]; System.out.println(arr[0]); > >
Related Article — Java Array
Clear ArrayList with clear() vs. removeAll()
Learn to clear an ArrayList or empty an ArrayList in Java. Clearing a list means removing all elements from the list. It is the same as resetting the list to its initial state when it has no element stored in it.
To clear an arraylist in java, we can use two methods.
Both methods will finally empty the list. But there is a difference in how they perform the empty operation.
The following Java program clears an arraylist using the clear() API.
ArrayList list = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e")); list.clear(); Assertions.assertEquals(0, list.size());
2. Clear ArrayList with removeAll()
Java program to remove all elements of an arraylist with removeAll() method. The removeAll() method removes all the elements in the current list that are present in the specified collection.
In this example, we are passing the self-reference of the list to the removeAll() method.
ArrayList list = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e")); list.removeAll(list); Assertions.assertEquals(0, list.size());
3. Difference between clear() and removeAll()
As I said before, both methods empty a list. But the difference lies in how they make the list clear. Let’s see the code for both methods to understand the actions they perform.
The clear() method is simple. It iterates over the list and assigns null to each index in the list.
In removeAll() method, it first checks if the element is present or not using contains() method. If the element is present then it is removed from the list. This happens for all the elements in the loop.
public boolean removeAll(Collection c) < Objects.requireNonNull(c); return batchRemove(c, false); >private boolean batchRemove(Collection c, boolean complement) < final Object[] elementData = this.elementData; int r = 0, w = 0; boolean modified = false; try < for (; r < size; r++) if (c.contains(elementData[r]) == complement) elementData[w++] = elementData[r]; >finally < // Preserve behavioral compatibility with AbstractCollection, // even if c.contains() throws. if (r != size) < System.arraycopy(elementData, r, elementData, w, size - r); w += size - r; >if (w != size) < // clear to let GC do its work for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w; size = w; modified = true; >> return modified; >
By going through the sourcecode of both methods, we can safely say that clear() method gives much better performance because of less number of statements it executes.
The removeAll() method lack in performance because of extra calls to contains() method. But, still removeAll() method is useful in cases such as merge two arraylists without duplicate elements.