Java Programs

Java Practice

Add object/element to the List at specified index in Java

Here, we are going to learn how to add object/element to the list at specified index in java?
Submitted by IncludeHelp, on October 11, 2018

We have to create a List and add objects/elements to the List and given indexes in java.

Java - Adding object/element to the List at specified index

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.


List.add(index, element);


  • 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


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 

Java program to add object/element to the List at specified index

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.

import java.util.*;

public class ListExample {
  public static void main(String[] args) {
    //creating a list of integers 
    List < Integer > int_list = new ArrayList < Integer > ();

    //adding some of the elements

    //printing the empty List
    System.out.print("int_list= ");

    //adding elements by specifying index 
    int_list.add(0, 5); //will add 5 at 0th index 
    int_list.add(3, 7); //will add 7 at 3rd index 

    //printing thed list 
    System.out.print("int_list= ");


int_list= [10, 20, 30, 40, 50]
int_list= [5, 10, 20, 7, 30, 40, 50]

Java List Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.