Java ArrayList - remove() Method
The java.util.ArrayList.remove() method is used to remove the element at the specified position in the list. It shifts any subsequent elements to the left by subtracting one from their indices. Every removal of element results into reducing the list size by one unless the list is empty.
Syntax
public E remove(int index)
Here, E is the type of element maintained by the container.
Parameters
index |
Specify index number of the element which need to be removed from the list. |
Return Value
Returns the removed element of the list.
Exception
Throws IndexOutOfBoundsException, if the index is out of range (index < 0 || index >= size()).
Example:
In the example below, the java.util.ArrayList.remove() method is used to remove the element at the specified position in given list.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating an ArrayList ArrayList<Integer> MyList = new ArrayList<Integer>(); //populating ArrayList MyList.add(10); MyList.add(20); MyList.add(30); MyList.add(40); //printing linkedlist System.out.println("MyList contains: "+ MyList); //delete element at index=2 MyList.remove(2); //printing linkedlist System.out.println("MyList contains: "+ MyList); } }
The output of the above code will be:
MyList contains: [10, 20, 30, 40] MyList contains: [10, 20, 40]
❮ Java.util - ArrayList