在特定索引之后从列表中删除所有元素 [英] Remove all elements from a List after a particular index
问题描述
List / ArrayList中是否有任何方便的方法可以在特定索引之后删除List的所有元素。而不是手动循环通过它来移除。
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.
为了更加解释,如果我有10个元素的列表,我想提到索引3然后索引后的所有元素3被删除,我的列表现在只包含4个元素(从0开始计算)
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)
推荐答案
list.subList(4, list.size()).clear();
子列表操作反映在原始列表中,因此清除了从索引4到列表的所有内容。 size()
exclusive,又名索引后的所有内容3.范围删除专门用作文档中的示例:
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:
此方法消除了对显式范围操作的需要(对于数组通常存在的
排序)。任何期望
列表的操作都可以通过传递子列表视图
而不是整个列表来用作范围操作。例如,以下习语从列表中删除
元素范围:
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();
这篇关于在特定索引之后从列表中删除所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!