Read Also: how ArrayList add(Object) method works internally in Java
According to Oracle docs, it removes the element at the specified position in the ArrayList. Also, it shifts any subsequent elements to the left i.e. index-1.
Syntax:
The syntax of the method is:
public Object remove(int index)
Parameters:
index: The index at which the element needs to be removed.
Exception:
remove(index) method throws IndexOutOfBoundsException.
remove(int index) example:
1. Remove String elements at the specified index from the ArrayList
In the below example, we have created an object of ArrayList of String type. Then we added elements to it by using add(element) method. After that, we are removing three elements at index 0, 2, and 3 respectively by using the remove(index) method. import java.util.*;
public class RemoveMethodExample {
public static void main(String args[]) {
// Creating an object of ArrayList of String Type
ArrayList<String> list = new ArrayList<>();
list.add("AA");
list.add("BB");
list.add("CC");
list.add("DD");
list.add("AA");
list.add("ZZ");
System.out.println("Given ArrayList before remove method: ");
for(String str : list) {
System.out.println(str);
}
// Using remove(element) method, removing 1st element, size() reduces by 1
list.remove(0);
// Using remove(element) method, removing 3rd element from the remaining list
list.remove(2);
// Using remove(element) method, removing 4th element from the remaining list
list.remove(3);
System.out.println("ArrayList after applying remove method: ");
for(String str2 : list) {
System.out.println(str2);
}
}
}
Output
Given ArrayList before remove method:
AA
BB
CC
DD
AA
ZZ
ArrayList after applying remove method:
BB
CC
AA
2. Remove Integer elements at the specified index from the ArrayList
In the below example, we have created an object of ArrayList of Integer type. After adding the elements using add(element) method, we are removing the elements using the remove(index) method.
import java.util.*;
public class RemoveMethodExample2 {
public static void main(String args[]) {
// Initializing an object of ArrayList of Integer Type
ArrayList<Integer> list2 = new ArrayList<>();
list2.add(23);
list2.add(34);
list2.add(45);
list2.add(56);
list2.add(25);
list2.add(33);
System.out.println("Integer ArrayList before remove method: ");
for(Integer i : list2) {
System.out.println(i);
}
// Using remove(element) method, removing 2nd element, size() reduces by 1
list2.remove(1);
// Using remove(element) method, removing 1st element from the remaining list
list2.remove(0);
System.out.println("Integer ArrayList after applying remove method: ");
for(Integer i2 : list2) {
System.out.println(i2);
}
}
}
Output
Integer ArrayList before remove method:
23
34
45
56
25
33
Integer ArrayList after applying remove method:
45
56
25
33
That's all for today. Please mention in the comments in case you have any questions related to remove(int index) method example of ArrayList in Java.