Java Collection How to - Replace Elements in a List








Question

We would like to know how to replace Elements in a List.

Answer

The object being replaced is returned by the set() method.

    
import java.util.Arrays;
import java.util.List;
public class MainClass {
  public static void main(String[] a) {
    List list = Arrays.asList(new String[] { "A", "B", "C", "D" });
    list.set(2, "X");
    System.out.println(list);
  }
}

The code above generates the following result.