Java Collection How to - Add element to the end of a List/in the middle of a List








Question

We would like to know how to add element to the end of a List/in the middle of a List.

Answer

    
import java.util.ArrayList;
import java.util.List;
/*from   w  ww  .  jav  a  2 s  .  c o  m*/
public class MainClass {
  public static void main(String args[]) throws Exception {
    // Create/fill collection
    List list = new ArrayList();
    list.add("A");
    list.add("B");
    list.add("C");
    System.out.println(list);
  }
}

The code above generates the following result.

in the middle of a List

import java.util.ArrayList;
import java.util.List;
/*  w  w  w .  j a va  2  s  .co m*/
public class MainClass {
  public static void main(String args[]) throws Exception {

    List list = new ArrayList();
    list.add("A");
    list.add("B");
    list.add("C");
    list.add(1, "G");

    System.out.println(list);

  }
}

The code above generates the following result.