如何在java中使用remove()
方法删除列表中的元素?使用集合概念。
通常我知道要使用remove()
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
// create an empty array list with an initial capacity
ArrayList<String> arrlist = new ArrayList<String>(5);
// use add() method to add values in the list
arrlist.add("G");
arrlist.add("E");
arrlist.add("F");
arrlist.add("M");
System.out.println("Size of list: " + arrlist.size());
// let us print all the values available in list
for (String value : arrlist) {
System.out.println("Value = " + value);
}
// Removes element "E"
arrlist.remove("E");
System.out.println("Now, Size of list: " + arrlist.size());
// let us print all the values available in list
for (String value : arrlist) {
System.out.println("Value = " + value);
}
}
}
答案 0 :(得分:0)
我会玩,但这是一种欺骗,因为在AbstractCollection中明显的clear()实现在内部使用了Iterator remove()方法。如果这不是想要的,那么反对意见可能会澄清这个问题。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> data = new ArrayList<String>(Arrays.asList(new String[] { "a",
"b", "c", "d" }));
System.out.println(data);
funnyRemove(data, 2);
System.out.println(data);
}
public static <T> void funnyRemove(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);
}
}