Java Collection How to - Keep List index fixed while removing data








Question

We would like to know how to keep List index fixed while removing data.

Answer

import java.util.ArrayList;
//from w w w.  j av a 2s  .c o m
public class Main {
  public static void main(String[] args) {
    ArrayList<Integer> a = new ArrayList<>();
    a.add(1);
    a.add(5);
    a.add(1);

    a.set(1, null);
    System.out.println(a.get(1));
    System.out.println(a);
  }
}

The code above generates the following result.