We have to create a List and add objects/elements to the List and given indexes in java.
To add any object/element at given index to the List, we use, List.add() method - which is a method of List and used to inserts object/element at given index.
Syntax:
List.add(index, element);
Here,
- index is the position of the list, where we have to insert the element
- element is the value or any object that is to be added at given index
Example:
L.add(0,10); //adds 10 at 0th index
L.add(1,20); //adds 20 at 1st index
L.add(3,30); //adds 30 at 2nd index
Program:
Here, we are creating a list of integer named int_list with some of the initial elements and we will add some of the elements at given indexes.
Output