从 List 中删除特定索引后的所有元素

在 List/ArrayList 中,有没有什么方便的方法可以在特定索引后删除 List 的所有元素。而不是手动循环删除。

为了更好地解释,如果我有一个包含10个元素的列表,我想提到索引3,然后索引3之后的所有元素都被删除,我的列表现在只包含4个开始的元素(从0开始计数)

57198 次浏览
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:

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();

Using sublist() and 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());
}
}