Adding element to ArrayList at specified index position

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

 

ArrayList :

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

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

 

Example: Adding element to ArrayList at specified index position

Below ArrayList example depicts

  • initially add 7 elements and iterate using regular for-loop
  • adding new element at 5th index position (i.e.; as a 6th element)
  • and again iterate through ArrayList elements using enhanced for-loop

AddElementAtSpecifiedIndexPosition.java

package in.bench.resources.java.collections;

import java.util.ArrayList;

public class AddElementAtSpecifiedIndexPosition {

	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 elements using for-loop\n");
		for(int index = 0; index < al.size(); index++) {
			System.out.println("index-" + index 
					+ "  " + al.get(index));
		}


		// adding new element at 5th index position
		al.add(5, "Narayan Murthy");

		// Iterating using enhanced for-loop
		System.out.println("\n\nIterating "
				+ "ArrayList elements 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
Narayan Murthy
Francisco D’Souza
null

Explanation:

  • element at 5th index position is shifted one-down and correspondingly other elements afterwards
  • new element added at 5th index position
  • 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 !!

Remove element from ArrayList at specified index position
How to get size or length of an ArrayList