The List interface extends the Collection interface and stores a sequence of elements. The List interface provides two methods to efficiently insert and delete multiple elements at any point in the list. Unlike sets, lists allow duplicate elements and multiple null values if null values are allowed in the list. List provides add and remove methods to add/remove elements. In order to clear the list or remove all elements from the list, we can use the clear() method of List. We can also use the removeAll() method to achieve the same effect as the clear() method.
In this article, we will introduce the clear() and removeAll() methods with corresponding examples.
void clear()
Removes all elements from this list.
The list will be empty after this call returns.
UnsupportedOperationException - if this list does not support clear operations.
boolean removeAll(Collection<?> c)
Removes from this list all elements contained in the specified collection.
c< /strong> - The collection containing the elements to be removed from this list.
Returns True if this list changed as a result of the call p>
##UnsupportedOperationException - if this list does not support the removeAll operation.
li>ClassCastException - if the class of an element in this list is incompatible with the specified collection (optional).
NullPointerException - If this list contains null elements and the specified collection does not allow null elements (optional), or the specified collection is null.
package com.tutorialspoint; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CollectionsDemo { public static void main(String[] args) { List<Integer> list = new ArrayList<>(Arrays.asList(0,1,2,3,4,5,6,7,8,9)); System.out.println("List: " + list); list.clear(); System.out.println("Cleared List: " + list); } }
List: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Cleared List: []
package com.tutorialspoint; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CollectionsDemo { public static void main(String[] args) { List<Integer> list = new ArrayList<>(Arrays.asList(0,1,2,3,4,5,6,7,8,9)); System.out.println("List: " + list); list.removeAll(list); System.out.println("Cleared List: " + list); } }
List: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Cleared List: []
The above is the detailed content of How to delete all elements of ArrayList in Java?. For more information, please follow other related articles on the PHP Chinese website!