 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Adding elements in the middle of an ArrayList in Java
Elements can be added in the middle of an ArrayList by using the java.util.ArrayList.add() method. This method has two parameters i.e. the index at which to insert the element in the ArrayList and the element itself. If there is an element already present at the index specified by ArrayList.add() then that element and all subsequent elements shift to the right by one.
A program that demonstrates this is given as follows −
Example
import java.util.ArrayList; import java.util.List; public class Demo { public static void main(String args[]) throws Exception { List aList = new ArrayList(); aList.add(0, "Apple"); aList.add(1, "Mango"); aList.add(2, "Banana"); aList.add(1, "Melon"); aList.add(3, "Guava"); System.out.println("The ArrayList elements are: " + aList); } }  Output
The ArrayList elements are: [Apple, Melon, Mango, Guava, Banana]
Now let us understand the above program.
The ArrayList aList is created. Then ArrayList.add() is used to add the elements at the specified position in the ArrayList, including in the middle. Finally, the ArrayList is displayed. A code snippet which demonstrates this is as follows −
List aList = new ArrayList(); aList.add(0, "Apple"); aList.add(1, "Mango"); aList.add(2, "Banana"); aList.add(1, "Melon"); aList.add(3, "Guava"); System.out.println("The ArrayList elements are: " + aList);Advertisements
 