+-
java – 在特定索引之后从List中删除所有元素
在List / ArrayList中是否有任何方便的方法可以在特定索引之后删除List的所有元素.而不是手动循环通过它来删除.

更具说明性,如果我有一个包含10个元素的列表,我想提到索引3,然后删除索引3之后的所有元素,我的列表现在只包含4个元素(从0开始计数)

最佳答案
list.subList(4, list.size()).clear();

Sublist operations are reflected in the original list,所以这将清除从索引4包含到list.size()的所有内容,a.k.a.索引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:

06001

点击查看更多相关文章

转载注明原文:java – 在特定索引之后从List中删除所有元素 - 乐贴网