Java 在特定索引之后从列表中删除所有元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22802232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove all elements from a List after a particular index
提问by Abhi
Is there any convenient way in List/ArrayList by which we can remove all elements of a List after a particular index. Instead of manually looping through it for removing.
在 List/ArrayList 中是否有任何方便的方法可以在特定索引之后删除 List 的所有元素。而不是手动循环遍历它以进行删除。
To be more explanatory, if I have a list of 10 elements, I want to mention index 3 and then all elements after index 3 gets removed and my list would consist of only starting 4 elements now (counts from 0)
更详细地说,如果我有一个包含 10 个元素的列表,我想提到索引 3,然后索引 3 之后的所有元素都被删除,我的列表现在只包含 4 个元素(从 0 开始计数)
采纳答案by user2357112 supports Monica
list.subList(4, list.size()).clear();
Sublist operations are reflected in the original list, so this clears everything from index 4 inclusive to list.size()
exclusive, a.k.a. everything after index 3. Range removal is specifically used as an example in the documentation:
子列表操作反映在原始列表中,因此这会清除从索引 4 到list.size()
独占的所有内容,也就是索引 3 之后的所有内容。文档中专门使用范围删除作为示例:
This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a list can be used as a range operation by passing a subList view instead of a whole list. For example, the following idiom removes a range of elements from a list:
list.subList(from, to).clear();
此方法消除了对显式范围操作(数组通常存在的排序)的需要。通过传递子列表视图而不是整个列表,任何需要列表的操作都可以用作范围操作。例如,以下习语从列表中删除一系列元素:
list.subList(from, to).clear();
回答by AJJ
Using sublist() and clear(),
使用 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());
}
}