In the following example, we will show you the method of adding elements in the specified position in the index list using add (int index, Object element) method of List Interface in java.
add (int index, Object element) method of List Interface in java.
In the following example, we will show you the method of adding elements in the specified position at the index in list using add (int index, Object element) method of List Interface in java.
Syntax
void add (int index, Object element)
This method does not return any value.
In thismethod you can insert an element into the list at the specified position. It inserts an element at the current position and replace the new element with old element and shifts the old element to it's right by adding 1 into its index, if any element is positioned at that index. It increment the index only at one place to it's right. It can not exceed the range of index when the size of index is limited.
Parameter description:
int index - It takes an integer value for positioning the element at specific place (into list).
Object element - It takes an object type element (value) what you want to insert into the list.
Example of add (int index, Object element) method
In this example we will show you, how does an add (int index, Object element) method work in List interface. This Example will help you to understand how an element can be added into the list. Through this example we will show you how an element can be added to a specific place and what will be the effect occur into a list. This example will add the elements into the list, and count the number of elements from list before and after adding the elements.
Example:-
package package Devmanuals.com; import java.util.List; import java.util.ArrayList; public class ListAdd { public static void main(String[] args) { List olist = new ArrayList(); olist.add("Dev"); olist.add("Manuals"); System.out.println("The elements are: " + olist); System.out.println("The Size of the list is: " + olist.size()); olist.add(2, "com"); System.out .println("After the addition of element at index 2 the new element =" + olist); System.out.println("The Size of the list after addition is: " + olist.size()); } }
Output:-
The elements are: [Dev, Manuals] The Size of the list is: 2 After the addition of element at index 2 the new element =[Dev, Manuals, com] The Size of the list after addition is: 3 |
[ 0 ] Comments