ArrayList – Delete Nth Element

To delete Nth element of an ArrayList in Java, we can use ArrayList.remove() method. ArrayList.remove() accepts index of the element to be removed and returns the removed element.

More about ArrayList.remove() method with Examples.

Example 1 – Delete Nth Element in ArrayList

In the following example, we will use remove() method to delete the second element of the ArrayList. N is passed as argument to remove() method.

DeleteElement.java

import java.util.ArrayList;

public class Example {
  public static void main(String[] args) {
	  ArrayList<String> arrayList = new ArrayList<String>();  
	  arrayList.add("a");  
	  arrayList.add("b");  
	  arrayList.add("c"); 
	  arrayList.add("d");
	  arrayList.add("e");
	  System.out.println("Original ArrayList  : " + arrayList);
	  
	  int index = 2;
	  arrayList.remove(index);
	  System.out.println("Resulting ArrayList : " + arrayList);
  }
}

Output

Original ArrayList  : [a, b, c, d, e]
Resulting ArrayList : [a, b, d, e]

Note: If the index provided to the remove() function exceeds the size of the ArrayList, java.lang.IndexOutOfBoundsException occurs. To prevent this, use Java Try Catch to handle IndexOutOfBoundsException.

ADVERTISEMENT

Conclusion

In this Java Tutorial, we learned how to delete an element present at index N of a given ArrayList.