Java ArrayList remove() Method
Example
Remove items from a list:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
cars.remove(0);
System.out.println(cars);
}
}
Definition and Usage
The remove()
method removes an item from the list, either by position or by value. If a position is specified then this method returns the removed item. If a value is specified then it returns true
if the value was found and false
otherwise.
If a value is specified and multiple elements in the list have the same value then only the first one is deleted.
If the list contains integers and you want to delete an integer based on its value you will need to pass an Integer
object. See More Examples below for an example.
Syntax
One of the following:
public T remove(int index)
public boolean remove(Object item)
T
refers to the data type of items in the list.
Parameter Values
Parameter | Description |
---|---|
index | Required. The position of the item to be deleted. |
item | Required. The value of the item to be deleted. |
Technical Details
Returns: | If an object was passed as an argument then it returns true if the object was found in the list and false otherwise. If an index was passed then it returns the object which was removed. |
---|---|
Throws: | IndexOutOfBoundsException - If the index is less than zero, equal to the size of the list or greater than the size of the list. |
More Examples
Example
Remove an integer from the list by position and by value:
import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(5); list.add(8); list.add(9); list.add(1); list.remove(Integer.valueOf(1)); // Remove by object list.remove(1); // Remove by index System.out.println(list);
}}
Related Pages
❮ ArrayList Methods