Java Collection How to - Remove elements from list with out using remove method








Question

We would like to know how to remove elements from list with out using remove method.

Answer

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/* w  w  w.  jav a 2 s  .c  om*/
public class Main {
  public static void main(String[] args) {
    List<String> data = new ArrayList<String>(Arrays.asList(new String[] { "a",
        "b", "c", "d","f","g" }));
    System.out.println(data);
    removeWithoutUsingRemoveMethod(data, 2);
    System.out.println(data);
  }

  public static <T> void removeWithoutUsingRemoveMethod(List<T> list, int index) {
    if (index < 0 || index >= list.size()) {
      throw new IllegalArgumentException("index out of range");
    }
    List<T> part1 = new ArrayList<T>(list.subList(0, index));
    List<T> part2 = new ArrayList<T>(list.subList(index + 1, list.size()));
    list.clear();
    list.addAll(part1);
    list.addAll(part2);
  }

}

The code above generates the following result.