How to remove an element from ArrayList in Java?
ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This class is found in java.util package. With the introduction and upgradations in java versions, newer methods are being available as if we do see from Java8 perceptive lambda expressions and streams concepts were not available before it as it been introduced in java version8, so do we have more ways to operate over Arraylist to perform operations. Here we will be discussing a way to remove an element from an ArrayList.
While removing elements from ArrayList there can either we are operating to remove elements over indexes or via values been there in an ArrayList. We will be discussing both ways via interpreting through a clean java program.
Methods:
There are 3 ways to remove an element from ArrayList as listed which later on will be revealed as follows:
- Using remove[] method by indexes[default]
- Using remove[] method by values
- Using remove[] method over iterators
Note: It is not recommended to use ArrayList.remove[] when iterating over elements.
Method 1: Using remove[] method by indexes
It is a default method as soon as we do use any method over data structure it is basically operating over indexes only so whenever we do use remove[] method we are basically removing elements from indices from an ArrayList.
ArrayList class provides two overloaded remove[] methods.
- remove[int index]: Accept index of the object to be removed
- remove[Object obj]: Accept object to be removed
Let us figure out with the help of examples been provided below as follows:
Example:
// Java program to Remove Elements from ArrayList
// Using remove[] method by indices
// Importing required classes
import java.util.ArrayList;
import java.util.List;
// Main class
public class GFG {
// Main driver method
public static void main[String[] args]
{
// Creating an object of List interface with
// reference to ArrayList class
List al = new ArrayList[];
// Adding elements to our ArrayList
// using add[] method
al.add[10];
al.add[20];
al.add[30];
al.add[1];
al.add[2];
// Printing the current ArrayList
System.out.println[al];
// This makes a call to remove[int] and
// removes element 20
al.remove[1];
// Now element 30 is moved one position back
// So element 30 is removed this time
al.remove[1];
// Printing the updated ArrayList
System.out.println[al];
}
}
|
Now we have seen removing elements in an ArrayList via indexes above, now let us see that the passed parameter is considered an index. How to remove elements by value.
Method 2: Using remove[] method by values
Example:
// Java program to Remove Elements from ArrayList
// Using remove[] method by values
// Importing required classes
import java.util.ArrayList;
import java.util.List;
// Main class
public class GFG {
// Main driver method
public static void main[String[] args]
{
// Creating an object of List interface with
// reference to ArrayList
List al = new ArrayList[];
// Adding elements to ArrayList class
// using add[] method
al.add[10];
al.add[20];
al.add[30];
al.add[1];
al.add[2];
// Printing the current ArrayList
System.out.println[al];
// This makes a call to remove[Object] and
// removes element 1
al.remove[new Integer[1]];
// This makes a call to remove[Object] and
// removes element 2
al.remove[new Integer[2]];
// Printing the modified ArrayList
System.out.println[al];
}
}
|
Output :
[10, 20, 30,1 ,2] [10, 20, 30]Note: It is not recommended to use ArrayList.remove[] when iterating over elements.
Method 3: Using Iterator.remove[] method
This may lead to ConcurrentModificationException When iterating over elements, it is recommended to use Iterator.remove[] method.
Example:
// Java program to demonstrate working of
// Iterator.remove[] on an integer arraylist
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class GFG {
// Main driver method
public static void main[String[] args]
{
// Creating an ArrayList
List al = new ArrayList[];
// Adding elements to our ArrayList
// using add[] method
al.add[10];
al.add[20];
al.add[30];
al.add[1];
al.add[2];
// Printing the current ArrayList
System.out.println[al];
// Creating iterator object
Iterator itr = al.iterator[];
// Holds true till there is single element
// remaining in the object
while [itr.hasNext[]] {
// Remove elements smaller than 10 using
// Iterator.remove[]
int x = [Integer]itr.next[];
if [x < 10]
itr.remove[];
}
// Printing the updated ArrayList
System.out.print[al];
}
}
|
This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks.
1. ArrayList.remove[int index] – remove element from arraylist at specified index
This method removes the specified element E at the specified position in this list. It removes the element currently at that position and all subsequent elements are moved to the left [will subtract one to their indices].
Index start with 0.
public class ArrayListExample { public static void main[String[] args] { ArrayList namesList = new ArrayList[Arrays.asList[ "alex", "brian", "charles"] ]; System.out.println[namesList]; //list size is 3 //Add element at 1 index namesList.remove[1]; System.out.println[namesList]; //list size is 2 } }Program output.
[alex, brian, charles] [alex, charles]Java.util.ArrayList.remove[] Method
Remove Elements from ArrayList in Index Range
To remove elements from ArrayList present in the given Index Range, get those elements using subList[] and then clear them using clear[] method. You can call subList[] method on the ArrayList, with from-index and to-index integer values passed as arguments respectively to the method.
Following is a quick code example to remove the elements from ArrayList in range [fromIndex, toIndex].
boolean b = arraylist_1.subList[fromIndex, toIndex+1].clear;One is added to toIndex argument of subList, because subList only considers the elements until toIndex but not including toIndex position.
There is a protected method ArrayList.removeRange[] to remove all elements in the range. Since, the method is protected, we cannot use it publicly. But, if you create a subclass for ArrayList, then you can use removeRange[] method.
Example 1 – Remove Elements from ArrayList in Given Index Range
In the following program, we shall take an ArrayList of strings, and remove all the elements present in the index range [1, 3].
Java Program
import java.util.ArrayList; import java.util.Arrays; public class ArrayListExample { public static void main[String[] args] { ArrayList arraylist_1 = new ArrayList[ Arrays.asList["apple", "banana", "mango", "orange", "papaya", "plum"]]; int fromIndex = 1; int toIndex = 3; arraylist_1.subList[fromIndex, toIndex+1].clear[]; arraylist_1.forEach[element -> { System.out.println[element]; }]; } }Output
apple papaya plumConclusion
In this Java Tutorial, we learned how to remove all elements from the ArrayList present in the given range, using sublist[] and clear[] method.
Remove an Element from ArrayList in Java
ArrayList is similar to the array whose size can be modified. The ArrayList class is available in the Java.util package and extends the List interface. Adding and removing an element from the ArrayList is very easy by using its built-in methods add[] and remove[]. However, there is more than one way of removing an element from the ArrayList that are as follows:
- Using ArrayList.remove[] Method
- By index.
- By element
- Using Iterator.remove[] Method
- Using ArrayList.removeIf[] Method
All these three ways are best in their own, and can be used in some different scenario. Let's understand all these three ways, one by one.
Code Example To Remove Elements from ArrayList
Let's test the above theory with a simple code example of ArrayList with Integers. The following program has an ArrayList of Integers containing 1, 2, and 3 i.e. [1, 2, 3], which corresponds exactly to the index.package test; import java.util.ArrayList; import java.util.List; /** * * @author //java67.blogspot.com */ public class JavaTutorial{ /** * @param args the command line arguments */ public static void main[String[] args] { List numbers = new ArrayList[]; numbers.add[1]; numbers.add[2]; numbers.add[3]; System.out.println["ArrayList contains : " + numbers]; // Calling remove[index] numbers.remove[1]; //removing object at index 1 i.e. 2nd Object, which is 2 //Calling remove[object] numbers.remove[3]; } } Output: ArrayList contains : [1, 2, 3] Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 2 at java.util.ArrayList.rangeCheck[ArrayList.java:635] at java.util.ArrayList.remove[ArrayList.java:474] at test.Test.main[Test.java:33] Java Result: 1
You can see that the second call is also treated as remove[index]. The best way to remove ambiguity is to take out autoboxing and provide an actual object, as shown below.
System.out.println["ArrayList Before : " + numbers]; // Calling remove[index] numbers.remove[1]; //removing object at index 1 i.e. 2nd Object, which is 2 //Calling remove[object] numbers.remove[new Integer[3]]; System.out.println["ArrayList After : " + numbers]; Output : ArrayList Before : [1, 2, 3] ArrayList After : [1]
This time, it works, but I am afraid of lazy developers like me, which take autoboxing for granted. Now let's take a look at removing the object from ArrayList while Iterating over them. You must be familiar with Iterator in Java, before proceeding further.