In this article, we will learn how to remove a specified element from an ArrayList in Java.
Java Program to Remove Specified Element From ArrayList
This can be done by using a simple built-in method remove(Object obj)
of the ArrayList class.
Syntax:
public boolean remove(Object obj)
Parameters –
- Particular element to be removed
Let’s see the program to understand it more clearly.
Method: Java Program to Remove Specified Element From ArrayList By Using remove() Method
Approach:
- Create an ArrayList say
al
and add elements into it usingadd()
method. - Use the
remove(Object obj)
method defined above for different test cases (element in the list) as given in the below code. - Display the updated ArrayList
Note:
- If the specified element which needs to be removed from ArrayList is not present then the method will return false.
- When there are duplicate elements, then first occurrence of specified element is removed from the ArrayList.
Program:
import java.util.ArrayList; public class Main { public static void main(String args[]) { //String ArrayList ArrayList<String> al = new ArrayList<String>(); //Adding elements 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("P"); //Removing X (Index - 3) from the remaining list al.remove("X"); // Displaying Remaining elements of ArrayList System.out.println("ArrayList After removal:"); for(String ele: al) { System.out.println(ele); } } }
Output: ArrayList before removal : P Q R X S T ArrayList After removal: Q R S T
Provided list of Simple Java Programs is specially designed for freshers and beginners to get familiarize with the concepts of Java programming language and become pro in coding.