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

 

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

 

Example: 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)
  • and 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

 

References:

 

Happy Coding !!
Happy Learning !!

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