How to insert an object in an ArrayList at a specific position in java?


The add() method of the ArrayList class helps you to add elements to an array list. It has two variants −

  • add(E e) − This method accepts an object/elements as a parameter and adds the given element at the end of the list.

  • public void add(int index, E element) − This method accepts an element and an integer value representing the position at which we need to insert it and inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

Therefore using the add() method that accepts index value, you can add elements to the list at the required position.

Example

 Live Demo

import java.util.ArrayList;
import java.util.Iterator;
public class OccurenceOfElements {
   public static void main(String args[]) {
      ArrayList <String> list = new ArrayList<String>();
      //Instantiating an ArrayList object
      list.add("JavaFX");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      list.add("OpenNLP");
      list.add("JOGL");
      list.add("Hadoop");
      list.add("HBase");
      list.add("Flume");
      list.add("Mahout");
      list.add("Impala");
      System.out.println("Contents of the array list (first to last): ");
      Iterator<String> it = list.iterator();
      while(it.hasNext()) {
         System.out.print(it.next()+", ");
      }
      //Adding elements at the 6th position:
      list.add(6, "Hadoop");
      it = list.iterator();
      System.out.println();
      System.out.println("Contents of the array list after inserting new element: ");
      while(it.hasNext()) {
         System.out.print(it.next()+" ");
      }
   }
}

Output

Contents of the array list (first to last):
JavaFX, Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala,
Contents of the array list after inserting new element:
JavaFX Java WebGL OpenCV OpenNLP JOGL Hadoop Hadoop HBase Flume Mahout Impala
raja
Published on 15-Oct-2019 10:28:44
Advertisements