The remove() method removes the single element from the arraylist. Show
Exampleimport java.util.ArrayList; class Main { public static void main(String[] args) { // create an ArrayList ArrayList<Integer> primeNumbers = new ArrayList<>(); primeNumbers.add(2); primeNumbers.add(3); primeNumbers.add(5); System.out.println("ArrayList: " + primeNumbers);// remove element at index 2 int removedElement = primeNumbers.remove(2); System.out.println("Removed Element: " + removedElement); } } // Output: ArrayList: [2, 3, 5] // Removed Element: 5The syntax of the remove() method is: // remove the specified element arraylist.remove(Object obj) // remove element present in the specified index arraylist.remove(int index)Here, arraylist is an object of the ArrayList class. remove() ParametersThe remove() method takes a single parameter.
If the same element obj is present in multiple location, then the element that appear first in the arraylist is removed. remove() Return Value
Note: If the specified index is out of range, the method throws IndexOutOfBoundsException. Example 1: Remove the Specified Element from the ArrayListimport java.util.ArrayList; class Main { public static void main(String[] args) { // create an ArrayList ArrayList<String> languages = new ArrayList<>(); // insert element to the arraylist languages.add("JavaScript"); languages.add("Java"); languages.add("Python"); System.out.println("ArrayList: " + languages);// remove the element Java boolean result = languages.remove("Java"); System.out.println("Is element Java removed? " + result); System.out.println("ArrayList after remove(): " + languages); } }Output ArrayList: [JavaScript, Java, Python] Is element Java removed? true ArrayList after remove(): [JavaScript, Python]In the above example, we have created a arraylist named languages. The arraylist stores the name of programming languages. Here, we have used the remove() method to remove the element Java from the arraylist. Example 2: Remove the Element From the Specified Positionimport java.util.ArrayList; class Main { public static void main(String[] args) { // create an ArrayList ArrayList<String> languages = new ArrayList<>(); // insert element to the arraylist languages.add("JavaScript"); languages.add("Java"); languages.add("Python"); System.out.println("ArrayList: " + languages);// remove the element from position 2 String element = languages.remove(2); System.out.println("ArrayList after remove(): " + languages); System.out.println("Removed Element: " + element); } }Output ArrayList: [JavaScript, Java, Python] ArrayList after remove(): [JavaScript, Java] Removed Element: PythonIn the above example, we have created an arraylist named languages. Notice the expression, languages.remove(2)Here, the remove() returns and removes the element present at position 2 (i.e. Python). Example 3: Remove the First Occurrence of the Elementimport java.util.ArrayList; class Main { public static void main(String[] args) { // create an ArrayList ArrayList<Integer> randomNumbers = new ArrayList<>(); // add element to the arraylist randomNumbers.add(22); randomNumbers.add(13); randomNumbers.add(35); randomNumbers.add(13); randomNumbers.add(40); System.out.println("ArrayList: " + randomNumbers);// remove the first occurrence of 13 boolean result = randomNumbers.remove(Integer.valueOf(13)); System.out.println("Is element 13 removed? " + result); System.out.println("ArrayList after remove(): " + randomNumbers); } }Output ArrayList: [22, 13, 35, 13, 40] Is element 13 removed? true ArrayList after remove(): [22, 35, 13, 40]In the above example, we have created an arraylists named randomNumbers . In the arraylist, the element 13 is present in two locations. Notice the line, randomNumbers.remove(Integer.valueOf(13))Here,
Note: We can also remove all the elements from the arraylist using the clear() method. To learn more, visit Java ArrayList clear(). Java List remove() method is used to remove elements from the list. ArrayList is the most widely used implementation of the List interface, so the examples here will use ArrayList remove() methods. Java List remove() MethodsThere are two remove() methods to remove elements from the List.
List remove() method examplesLet’s look into some examples of remove() methods. 1. Remove element at given indexList<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); list.add("C"); list.add("B"); list.add("A"); System.out.println(list); String removedStr = list.remove(1); System.out.println(list); System.out.println(removedStr);Output: [A, B, C, C, B, A] [A, C, C, B, A] B2. IndexOutOfBoundsException with remove(int index) MethodList<String> list = new ArrayList<>(); list.add("A"); String removedStr = list.remove(10);Exception Output: Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 10 out of bounds for length 1 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70) at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248) at java.base/java.util.Objects.checkIndex(Objects.java:372) at java.base/java.util.ArrayList.remove(ArrayList.java:535) at com.journaldev.java.ArrayListRemove.main(ArrayListRemove.java:19)3. Unmodifiable List remove() UnsupportedOperationException ExampleList.of() method creates an unmodifiable list, so using remove() method will throw UnsupportedOperationException. jshell> List<String> list = List.of("a", "b"); list ==> [a, b] jshell> list.remove(1); | Exception java.lang.UnsupportedOperationException | at ImmutableCollections.uoe (ImmutableCollections.java:72) | at ImmutableCollections$AbstractImmutableList.remove (ImmutableCollections.java:108) | at (#64:1) jshell> list.remove("a"); | Exception java.lang.UnsupportedOperationException | at ImmutableCollections.uoe (ImmutableCollections.java:72) | at ImmutableCollections$AbstractImmutableCollection.remove (ImmutableCollections.java:79) | at (#65:1) jshell>4. Removing an object from the listList<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); list.add("C"); list.add("B"); list.add("A"); System.out.println(list); boolean isRemoved = list.remove("C"); System.out.println(list); System.out.println(isRemoved); isRemoved = list.remove("X"); System.out.println(list); System.out.println(isRemoved);Output: [A, B, C, C, B, A] [A, B, C, B, A] true [A, B, C, B, A] falseReferences
There are two ways to remove all elements of an ArrayList in Java, either by using clear() or by using the removeAll() method. Both methods are defined in the java.util.List and java.util.Collection interface, hence they are available not just to ArrayList but also to Vector or LinkedList, etc. Both elements remove all objects from ArrayList but there is a subtle difference in how they do. The clear() method is straightforward, it traverses through the ArrayList and sets all indices to null, which means the ArrayList becomes empty and all elements become eligible to Garbage collection, provided there are no more references to them. The time taken by the clear() method is in O(n), which means the bigger the ArrayList the longer it will take to empty it. On the other hand, removeAll(Collection c) accepts a Collection and then iterate over List. At each iteration, it checks if the current element in the ArrayList is present in the Collection c using contains() method, which takes its O(n) time to confirm because it also uses Iterator instead of random access. So overall time taken to remove all elements using the removeAll() method is in order of O(n^2) which means time will increase in the quadratic of a number of elements in the array. This difference is not much if your ArrayList is small and just contains 10 to 100 elements but for a big ArrayList e.g. of 1 million objects, this time could be significant. This is also one of the frequently asked ArrayList questions from Java Interviews, so knowing the key difference will help you there as well. So the choice is yours, I suggest using clear() if you want to remove all elements from the ArrayList and use removeAll() if you want to remove selected elements given to you in a Collection. Let's see the example of both of them in Java. Here is a complete Java program to remove all elements and make an ArrayList empty in Java. This program demonstrates how you can remove all elements from a given ArrayList by using both the clear() and removeAll() methods. If you want to remove just a single element then you can use the remove() method as discussed here.The program prints all objects of ArrayList before and after calling the clear() and removeAll() method to show that method is actually working and the ArrayList is empty afterward. You can reuse the ArrayList by clearing it but make sure you don't do that in a multi-threading environment e.g. one thread is calling the clear() method while another thread is calling the add() method to insert elements. The ArrayList class is not thread-safe and sharing the same ArrayList between multiple threads will crate thread-safety-related problems and erroneous results. See Core Java for the Impatient to learn more about the problems of using ArrayList in muti-threading applications. Here is our complete Java program to demonstrate how to remove all elements from a give ArrayList in Java using the removeAll method.
That's all about how to remove all elements from an ArrayList in Java. As I said, clear() takes less time than removeAll() to remove all objects, hence you should always use clear() to make an ArrayList empty. But, if you are not removing all elements and a list of elements to be removed are provided to you in a Collection or List then use the removeAll() method. Other Java ArrayList tutorials for Java Programmers
|