- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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);
- Related Articles
- Adding elements to the end of the ArrayList in C#
- Sort Elements in an ArrayList in Java
- Copy all elements of ArrayList to an Object Array in Java
- How to remove the redundant elements from an ArrayList object in java?
- Add elements at the middle of a Vector in Java
- Remove all elements from the ArrayList in Java
- Remove all the elements from an ArrayList that are in another Collection in Java
- Get the size of an ArrayList in Java
- How to remove all elements of ArrayList in Java?
- Clear an ArrayList in Java
- Clone an ArrayList in Java
- Initialize an ArrayList in Java
- Find the Middle Element of an array in JAVA
- Search an element of ArrayList in Java
- Get the location of an element in Java ArrayList

Advertisements