How do you remove an element from an ArrayList from an index in Java?

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:

  1. Using remove[] method by indexes[default]
  2. Using remove[] method by values
  3. 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




// 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];
}
}
Output [10, 20, 30, 1, 2] [10, 1, 2]

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




// 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




// 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];
}
}
Output [10, 20, 30, 1, 2] [10, 20, 30]

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.




Article Tags :
Java
Java-ArrayList
Java-Collections
java-list
Java-List-Programs
Practice Tags :
Java
Java-Collections
Read Full Article

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

Advertisements

Previous Page
Next Page

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 plum

Conclusion

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:

  1. Using ArrayList.remove[] Method
    1. By index.
    2. By element
  2. Using Iterator.remove[] Method
  3. 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.



Remove Object From ArrayList using Iterator

This is actually a subtle detail of Java programming, not obvious for first-timers, as the compiler will not complain, even if you use theremove[] method from java.util.ArrayList, while using Iterator.


You will only realize your mistake, when you see ConcurrentModificationException, which itself is misleading and you may spend countless hours finding another thread, which is modifying that ArrayList, because of Concurrent word. Let's see an example.

public static void main[String[] args] { List numbers = new ArrayList[]; numbers.add[101]; numbers.add[200]; numbers.add[301]; numbers.add[400]; System.out.println["ArrayList Before : " + numbers]; Iterator itr = numbers.iterator[]; // remove all even numbers while [itr.hasNext[]] { Integer number = itr.next[]; if [number % 2 == 0] { numbers.remove[number]; } } System.out.println["ArrayList After : " + numbers]; } Output : ArrayList Before : [101, 200, 301, 400] Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification[ArrayList.java:859] at java.util.ArrayList$Itr.next[ArrayList.java:831] at Testing.main[Testing.java:28]
You can ConcurrentModificationException, due to call to remove[] method from ArrayList. This is easy in simple examples like this, but in a real project, it can be really tough. Now, to fix this exception, just replace the call of numbers.remove[] to itr.remove[], this will remove the current object you are Iterating, as shown below :

System.out.println["ArrayList Before : " + numbers]; Iterator itr = numbers.iterator[]; // remove all even numbers while [itr.hasNext[]] { Integer number = itr.next[]; if [number % 2 == 0] { itr.remove[]; } } System.out.println["ArrayList After : " + numbers]; Output ArrayList Before : [101, 200, 301, 400] ArrayList After : [101, 301]
That’s all on this post about How to remove objects from ArrayList in Java. We have learned two ways to remove an object or element from ArrayList. By the way, You should always use remove[index] to delete objects, if you are not iterating, otherwise, always use Iterator's remove[] method for removing objects from ArrayList.

By the way, the above tips will work with any index-based List implementation.

Java ArrayList Remove Example

Here is the Java program to remove a given object from ArrayList in Java. In this example, I have used the second remove method, which deletes the given object from ArrayList. Anyway, since we have an ArrayList of String, you can use any of those method, its safe. You can also check thesize[] of ArrayList before and after removing elements.

Remember, size[]method gives total number of elements in ArrayList, so it should reduce by one. This is different than the size of array which is backing ArrayList, which will remain same. In our example, you can see that number of elements is gradually reduced after removal.

By using index you can easily remove the first or last element from ArrayList in Java. Since index starts at zero in ArrayList, you can remove the first element by passing zero to remove method like remove[0], and to remove the last element from ArrayList, you can pass size - 1 to remove[int index] method like remove[ArrayList.size[] - 1] will remove the last element from ArrayList. Remember, unlike an array, there is no length method in ArrayList, so you need to use the size[] method which returns a total number of elements in the ArrayList.

Time complexity of remove[int index] method is O[n] because it's not just delete the element at specified index but also shifts any subsequent elements to the left i.e. subtracts one from their indices. For example, if ArrayList has 10 elements and you removed the 4th element i.e. index 3 then all elements starting from 5th to 10th will shift lower e.g. 5th will come to 4th, 6th will come to 5th, and so on.

There is one more method removeAll[Collection c] which you can use to remove all elements specified in the given collection. This method return true if ArrayList changed by calling this method i.e. one more elements are removed. You can use this method to remove elements in bulk from ArrayList.

This method will throw ClassCastException if the class of the element of this list is not compatible with the class of the element in the given collection. It will also throw NullPointerException if this list contains a null element and specified collection doesn't permit null elements or the specified collection itself is null.

Though, you shouldn't use these methods when you are removing elements while iterating over ArrayList. In that case, you must use Iterator's remove[] method to avoid ConcurrentModificationException.

You can further join these Java collectionsand Stream API coursesto learn more about how to remove objects from ArrayList in Java. One of the most comprehensive yet easy-to-read books on Java programming.




Video liên quan

Bài Viết Liên Quan

Bài mới nhất

Chủ Đề