

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 an 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);
- Related Questions & Answers
- Insert an element into the ArrayList at the specified index in C#
- Remove the element at the specified index of the ArrayList in C#
- Get the index of a particular element in an ArrayList in Java
- Insert all elements of other Collection to Specified Index of Java ArrayList
- Replace an element at a specified index of the Vector in Java
- Get the last index of a particular element in an ArrayList in Java
- Search an element of ArrayList in Java
- Java Program to insert all elements of other Collection to specified Index of ArrayList
- Replace all occurrences of specified element of ArrayList with Java Collections
- How to replace an element of an ArrayList in Java?
- Get or set the element at the specified index in ArrayList in C#
- Check existence of an element in Java ArrayList
- Get the location of an element in Java ArrayList
- Retrieve an element from ArrayList in Java
- Insert an element into Collection at specified index in C#
Advertisements