将 ArrayList 缩小到新的大小 [英] Shrinking an ArrayList to a new size
本文介绍了将 ArrayList 缩小到新的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我真的需要自己实现吗?
Do I really need to implement it myself?
private void shrinkListTo(ArrayList<Result> list, int newSize) {
for (int i = list.size() - 1; i >= newSize; --i)
list.remove(i);
}
推荐答案
创建一个 sublist 包含您希望删除的元素范围,然后调用 clear
在返回的列表中.
Create a sublist with the range of elements you wish to remove and then call clear
on the returned list.
list.subList(23, 45).clear()
这是一个经过完整单元测试的代码示例!
Here's a fully unit tested code example!
// limit yourHappyList to ten items
int k = yourHappyList.size();
if ( k > 10 )
yourHappyList.subList(10, k).clear();
// sic k, not k-1
这篇关于将 ArrayList 缩小到新的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文