Java – Remove element from ArrayList at specified index position

In this article, we will discuss a simple example on ArrayList on how to remove an element at the specified index position

1. ArrayList :

We can use, remove(index) method of List interface to remove element at specified index position of invoking ArrayList which

  • allows duplicate elements
  • null elements insertion is possible
  • maintains insertion-order

2. Remove element from ArrayList at specified index-position

Below ArrayList example depicts,

  • Initially there are 7 elements
  • Iterating using regular for-loop
  • Removing element at 5th index-position (i.e.; 6th element)
  • Again iterate through ArrayList elements using enhanced for-loop

RemoveElementAtSpecifiedIndexPosition.java

package in.bench.resources.java.collections;

import java.util.ArrayList;

public class RemoveElementAtSpecifiedIndexPosition {

	public static void main(String[] args) {

		// creating ArrayList object of type String
		ArrayList<String> al = new ArrayList<String>();

		// adding elements to ArrayList object
		al.add("Sundar Pichai");
		al.add("Satya Nadella");
		al.add("Shiv Nadar");
		al.add("Shantanu Narayen");
		al.add("Sundar Pichai"); // duplicate object
		al.add("Francisco D’Souza");
		al.add(null); // null is allowed

		// Iterating using for-loop
		System.out.println("Iterating ArrayList using for-loop\n");
		for(int index = 0; index < al.size(); index++) {
			System.out.println("index-" + index
					+ "  "
					+ al.get(index));
		}

		// removing element at 5th index position
		al.remove(5);

		// Iterating using enhanced for-loop
		System.out.println("\n\nIterating "
				+ "ArrayList using enhanced for-loop\n");
		for(String str : al) {
			System.out.println(str);
		}
	}
}

Output:

Iterating ArrayList using for-loop

index-0  Sundar Pichai
index-1  Satya Nadella
index-2  Shiv Nadar
index-3  Shantanu Narayen
index-4  Sundar Pichai
index-5  Francisco D’Souza
index-6  null

Iterating ArrayList using enhanced for-loop

Sundar Pichai
Satya Nadella
Shiv Nadar
Shantanu Narayen
Sundar Pichai
null

Explanation:

  • element at 5th index position is removed and correspondingly other elements after 5th index position shifted one-up (to fill-up)
  • elements above 5th index position, is remain unchanged

From above example, ArrayList

  • allows duplicate elements
  • null object is allowed
  • while iterating insertion order is maintained

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - How to delete an element and delete all elements of an ArrayList
Java - Adding element to ArrayList at specified index position