Java List remove element using subList() method

Description

Java List remove element using subList() method


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

public class Main {
  public static void main(String[] args) {
    List<String> data = new ArrayList<String>(Arrays.asList(new String[] { "CSS",
        "HTML", "Java", "SQL","Javascript","C++" }));
    System.out.println(data);//ww w .  j  a v a2s. c  o m
    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);
  }

}



PreviousNext

Related