Saturday 11 April 2020

List: Replace element at specific index

‘List’ interface provide ‘set’ method, it is used to replace the element at the specified position in this list with the specified element.

Signature
E set(int index, E element);

Example
List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13);
primes.set(1, 17);

App.java
package com.sample.app;

import java.util.Arrays;
import java.util.List;

public class App {

 public static void main(String args[]) {
  List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13);

  System.out.println("primes : " + primes);

  System.out.println("Setting element at index 1 to 17");

  primes.set(1, 17);
  
  System.out.println("primes : " + primes);

 }
}

Output
primes : [2, 3, 5, 7, 11, 13]
Setting element at index 1 to 17
primes : [2, 17, 5, 7, 11, 13]


You may like

No comments:

Post a Comment