Java .remove()
Published Mar 21, 2022
The .remove() method is used for removing specified elements from instances of the ArrayList class.
Syntax
An element can be removed from an ArrayList instance by being passed to the .remove() method. It can be referenced either by value or index:
arrayListInstance.remove(element);
Example
In the example below, an empty ArrayList instance studentList is created and can hold String-type elements. Next, a few elements are added with the .add() method. Lastly, two students are removed from the ArrayList with .remove():
import java.util.ArrayList;public class Students {public static void main(String[] args) {ArrayList<String> studentList = new ArrayList<String>();studentList.add("John");studentList.add("Lily");studentList.add("Samantha");studentList.add("Tony");// Remove John via index, then Lily via valuestudentList.remove(0);studentList.remove("Lily");System.out.println(studentList);}}
The studentList output should look like this:
[Samantha, Tony]
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours