List / ArrayList中是否有任何方便的方法可以在特定索引之后删除List的所有元素。而不是手动循环通过它来移除。
更具说明性,如果我有10个元素的列表,我想提到索引3,然后删除索引3之后的所有元素,我的列表现在只包含4个元素(从0开始计数)
答案 0 :(得分:101)
list.subList(4, list.size()).clear();
Sublist operations are reflected in the original list,因此这将清除从索引4包含到list.size()
的所有内容,a.k.a.索引3之后的所有内容。范围删除专门用作文档中的示例:
这种方法消除了对显式范围操作的需要 排序通常存在于数组中)。任何期望的操作 list可以通过传递subList视图用作范围操作 而不是整个列表。例如,以下习语删除了一个 列表中的元素范围:
list.subList(from, to).clear();
答案 1 :(得分:9)
使用sublist()和clear(),
public class Count
{
public static void main(String[] args)
{
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5");
arrayList.subList(2, arrayList.size()).clear();
System.out.println(arrayList.size());
}
}
答案 2 :(得分:0)
或使用子列表中的元素创建一个新列表。
List<String> newSublist = new ArrayList<>(list.sublist(0, excludedIndex));
上一个答案的示例
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> originalList = new ArrayList<>();
originalList.add("0");
originalList.add("1");
originalList.add("2");
originalList.add("3");
originalList.add("4");
System.out.println("Original list: " + originalList);
List<String> viewSublist = originalList.subList(0, 2);
System.out.println("View of the original list: " + viewSublist);
List<String> res = new ArrayList<>(viewSublist);
System.out.println("Sublist result - new list: " + res);
originalList.set(1, "111"); // By changing original list, sublist view gets changed.
System.out.println("View of the original list after changing the original list: " + viewSublist);
System.out.println("Sublist result - new list after changing the original list - not affected: " + res);
}
}
打印:
Original list: [0, 1, 2, 3, 4]
View of the original list: [0, 1]
Sublist result - new list: [0, 1]
View of the original list after changing the original list: [0, 111]
Sublist result - new list after changing the original list - not affected: [0, 1]
https://www.geeksforgeeks.org/arraylist-sublist-method-in-java-with-examples/