How does the ArrayList remove method work?

Java.util.ArrayList.remove[] Method

Advertisements

Previous Page
Next Page

1. ArrayList remove[] method

The remove[] method is overloaded and comes in two variants:

  • boolean remove[Object o] – removes the first occurrence of the specified element from the list. Returns true is any element was removed from the list, else false.
  • Object remove[int index] throws IndexOutOfBoundsException – removes the element at the specified position in this list. Shifts any subsequent elements to the left. Returns the removed element from the list. Throws exception if argument index is invalid.

ArrayList and LinkedList remove[] methods in Java with Examples

List interface in Java [which is implemented by ArrayList and LinkedList] provides two versions of remove method.
boolean remove[Object obj] :
It accepts object to be removed. It returns true if it finds and removes the element. It returns false if the element to be removed is not present.

  • Removes the first occurrence of the specified element from given list, if the element is present. If the element is not present, the given list is not changed.
  • After removing, it shifts subsequent elements[if any] to left and decreases their indexes by 1.

It throws following exceptions
ClassCastException – if the type of the specified element is incompatible with this collection
[optional].
NullPointerException – if the specified element is null and this collection does not permit
null elements[optional].
UnsupportedOperationException – if the remove operation is not supported by this collection

Java




// A Java program to demonstrate working of list remove
// when Object to be removed is passed.
import java.util.*;
public class GFG
{
public static void main[String[] args]
{
// Demonstrating remove on ArrayList
List myAlist = new ArrayList[];
myAlist.add["Geeks"];
myAlist.add["Practice"];
myAlist.add["Quiz"];
System.out.println["Original ArrayList : " + myAlist];
myAlist.remove["Quiz"];
System.out.println["Modified ArrayList : " + myAlist];
// Demonstrating remove on LinkedList
List myLlist = new LinkedList[];
myLlist.add["Geeks"];
myLlist.add["Practice"];
myLlist.add["Quiz"];
System.out.println["Original LinkedList : " + myLlist];
myLlist.remove["Quiz"];
System.out.println["Modified LinkedList : " + myLlist];
}
}
Output Original ArrayList : [Geeks, Practice, Quiz] Modified ArrayList : [Geeks, Practice] Original LinkedList : [Geeks, Practice, Quiz] Modified LinkedList : [Geeks, Practice]

object remove[int index] :
It removes the element at given index. It returns the object that is removed.

  • After removing, it shifts subsequent elements[if any] to left and decreases their indexes by 1.
  • If the list contains int types, then this method is called when an int is passed [Please refer this for details]

It throws IndexOutOfBoundsException if index is out of bound,



Java




// A Java program to demonstrate working of list remove
// when index is passed.
import java.util.*;
public class GFG
{
public static void main[String[] args]
{
// Demonstrating remove on ArrayList
List myAlist = new ArrayList[];
myAlist.add["Geeks"];
myAlist.add["Practice"];
myAlist.add["Quiz"];
System.out.println["Original ArrayList : " + myAlist];
myAlist.remove["Quiz"];
System.out.println["Modified ArrayList : " + myAlist];
// Demonstrating remove on LinkedList
List myLlist = new LinkedList[];
myLlist.add["Geeks"];
myLlist.add["Practice"];
myLlist.add["Quiz"];
System.out.println["Original LinkedList : " + myLlist];
myLlist.remove[2];
System.out.println["Modified LinkedList : " + myLlist];
}
}
Output Original ArrayList : [Geeks, Practice, Quiz] Modified ArrayList : [Geeks, Practice] Original LinkedList : [Geeks, Practice, Quiz] Modified LinkedList : [Geeks, Practice]

Important Points:

  • Note that there is no direct way to remove elements in array as size of array is fixed. So there are no methods like add[], remove[], delete[]. But in Collection like ArrayList and Hashset, we have these methods. So it’s better to either convert array to ArrayList or Use Arraylist from first place when we need these methods.
  • It is not recommended to use remove[] of list interface when iterating over elements. This may lead to ConcurrentModificationException [Refer this for a sample program with this exception]. When iterating over elements, it is recommended to use Iterator.remove[] method. Please see this for details.

This article is contributed by Mohit Gupta. 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 - util package
Java-ArrayList
Java-Collections
Java-Functions
java-LinkedList
Practice Tags :
Java
Java-Collections
Read Full Article

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

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.

Video liên quan

Bài mới nhất

Chủ Đề