Q:

Replace an element at given index of a List with new element in Java

0

Given a list of the integers and we have to replace it an element from specified index with a new element in java.

To replace an element in the list - we use List.set() method.

List.set() method

List.set() method replaces an existing element at given index with new element and returns the old object/element.

Syntax:

    Object List.set(index, new_object);

Example:

    Input:
    List = [10, 20, 30, 40, 50]
    Index =1 
    new_element = 1000

    Output:
    Updated list =[10, 1000, 30, 40, 50]

 

All Answers

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

Program:

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);

    //replace elements
    int old_ele, new_ele, index;
    index = 0;
    new_ele = 12;
    old_ele = int_list.set(index, new_ele);
    System.out.println(old_ele + " is replace with " + new_ele);

    index = 2;
    new_ele = 24;
    old_ele = int_list.set(index, new_ele);
    System.out.println(old_ele + " is replace with " + new_ele);

    //printing updated list 
    System.out.println("updated list: " + int_list);
  }
};

Output

 
10 is replace with 12
30 is replace with 24
updated list: [12, 20, 24, 40, 50]

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

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now