How do I insert an item between two items in a list in Java?

JavaObject Oriented ProgrammingProgramming

We can insert element between two items of an array list easily using its add() method.

Syntax

void add(int index, E element)

Inserts the specified element at the specified position in this list (optional operation). Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

Type Parameter

  • − The runtime type of the element.

Parameters

  • index  − Index at which the specified element is to be inserted.

  • − Element to be inserted to this list.

Throws

  • UnsupportedOperationException − If the add operation is not supported by this list

  • ClassCastException − If the class of the specified element prevents it from being added to this list

  • NullPointerException − If the specified element is null and this list does not permit null elements

  • IllegalArgumentException − If some property of this element prevents it from being added to this list

  • IndexOutOfBoundsException − If the index is out of range (index < 0 || index > size())

Example

The following example shows how to insert elements in between items in the list using add() method.

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.List;

public class CollectionsDemo {
   public static void main(String[] args) {
      // Create a list object
      List<String> list = new ArrayList<>();

      // add elements to the list
      list.add("A");
      list.add("B");
      list.add("C");

      // print the list
      System.out.println(list);
      list.add(1,"B");
      System.out.println(list);
   }
}

Output

This will produce the following result −

[A, C, D]
[A, B, C, D]
raja
Updated on 09-May-2022 11:26:55

Advertisements