
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Insert Item Between Two Items in a List in Java
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
E − The runtime type of the element.
Parameters
index − Index at which the specified element is to be inserted.
e − 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]