In this tutorial, we will learn how to use the Java ArrayList class remove() method to remove an element from ArrayList in Java.
ArrayList remove Method Overview
The ArrayList class provides below two overloaded remove() methods:- remove(int index) - Removes the element at the specified position in this list (optional operation). Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the list.
- remove(Object o) - Removes the first occurrence of the specified element from this list, if it is present (optional operation).
Java ArrayList remove() Method Example
package com.javaguides.collections.arraylistexamples; import java.util.ArrayList; import java.util.List; public class RemoveElementsFromArrayListExample { public static void main(String[] args) { List < String > programmingLanguages = new ArrayList < > (); programmingLanguages.add("C"); programmingLanguages.add("C++"); programmingLanguages.add("Java"); programmingLanguages.add("Kotlin"); programmingLanguages.add("Python"); programmingLanguages.add("Perl"); programmingLanguages.add("Ruby"); System.out.println("Initial List: " + programmingLanguages); // Remove the element at index `5` programmingLanguages.remove(5); System.out.println("After remove(5): " + programmingLanguages); // Remove the first occurrence of the given element from the ArrayList // (The remove() method returns false if the element does not exist in the ArrayList) programmingLanguages.remove("Kotlin"); System.out.println("After remove(\"Kotlin\"): " + programmingLanguages); } }Output:
Initial List: [C, C++, Java, Kotlin, Python, Perl, Ruby]
After remove(5): [C, C++, Java, Kotlin, Python, Ruby]
After remove("Kotlin"): [C, C++, Java, Python, Ruby]
Reference
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course
Comments
Post a Comment