
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
Add Element to Specified Index of ArrayList in Java
An element can be added to the specified index of an ArrayList by using the java.util.ArrayList.add() method. This method has two parameters i.e. the specific 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, "Dog"); aList.add(1, "Cat"); aList.add(2, "Horse"); aList.add(2, "Pig"); aList.add(3, "Cow"); System.out.println("The ArrayList elements are: " + aList); } }
Output
The ArrayList elements are: [Dog, Cat, Pig, Cow, Horse]
Now let us understand the above program.
The ArrayList aList is created. Then ArrayList.add() is used to add the elements at the specified index in the ArrayList. Finally, the ArrayList is displayed. A code snippet which demonstrates this is as follows −
List aList = new ArrayList(); aList.add(0, "Dog"); aList.add(1, "Cat"); aList.add(2, "Horse"); aList.add(2, "Pig"); aList.add(3, "Cow"); System.out.println("The ArrayList elements are: " + aList);
Advertisements