Q:

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

belongs to collection: Java List Programs

0

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 

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

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
    int_list.add(10);
    int_list.add(20);
    int_list.add(30);
    int_list.add(40);
    int_list.add(50);

    //printing the empty List
    System.out.print("int_list= ");
    System.out.println(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= ");
    System.out.print(int_list);
  }
};

Output

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Get an element/object from given index of a List i... >>
<< Integer List Example (Create, Add elements, Remove...