Arraylist remove element: In this article, we will learn how to remove an element of an ArrayList from a specified Index by using Java programming language.
Java Program to Remove Element at Particular Index of ArrayList
This can be done by using a simple built-in method remove()
.
Syntax:
public Object remove(int index)
Parameters:
- Particular Index from which element to be removed.
Let’s see the program to remove element at particular index of ArrayList.
Method-1: Java Program to Remove Element at Particular Index of ArrayList By Using remove() Method
Approach:
- Create an ArrayList say
al
and add elements into it usingadd()
method. - Use the
remove(int index)
method defined above for different test cases (indexes) as given in the below code. - Display the updated ArrayList.
Program:
import java.util.ArrayList; public class Main { public static void main(String args[]) { //String ArrayList ArrayList<String> al = new ArrayList<String>(); al.add("P"); al.add("Q"); al.add("R"); al.add("X"); al.add("S"); al.add("T"); // Displaying before removing element System.out.println("ArrayList before removal :"); for(String ele: al) { System.out.println(ele); } //Removing P (Index - 0) al.remove(0); //Removing X (Index - 2) from the remaining list al.remove(2); // Displaying Remaining elements of ArrayList System.out.println("ArrayList After remove:"); for(String ele: al) { System.out.println(ele); } } }
Output: ArrayList before removal : P Q R X S T ArrayList After remove: Q R S T
Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.