java从列表中删除第一个“n”元素而不进行迭代
我需要一种从列表中删除项目的有效方法。如果出现某种情况,我需要从列表中删除第一个“n”元素。有人能建议最好的方法吗?请记住:性能是我的一个因素,所以我需要一种比评级更快的方法。谢谢
我正在考虑一种方法,通过这种方法,第n项可以作为列表的开始,这样0-n项就可以被垃圾收集。可能吗
你可以在下面搜索框中键入要查询的问题!
我需要一种从列表中删除项目的有效方法。如果出现某种情况,我需要从列表中删除第一个“n”元素。有人能建议最好的方法吗?请记住:性能是我的一个因素,所以我需要一种比评级更快的方法。谢谢
我正在考虑一种方法,通过这种方法,第n项可以作为列表的开始,这样0-n项就可以被垃圾收集。可能吗
# 1 楼答案
您可以使用
ArrayList.removeRange(int fromIndex, int toIndex)
引用documentation:
# 2 楼答案
单线解决方案是:
从从索引
n
开始并在索引m - 1
处停止的列表中删除m - n
元素# 3 楼答案
如果性能对您来说是关键,那么我不确定使用ArrayList中的内置函数是一条出路。我怀疑它们的运行速度比O(n)快,遗憾的是Java文档对此一无所知。也许你应该研究一些定制的结构,比如Rope
# 4 楼答案
如果您经常修改列表,为什么不使用LinkedList类呢
如果使用ArrayList类,则在删除项时,数组必须始终移动
# 5 楼答案
Jigar Joshi的答案已经包含了您需要的解决方案。我想添加一些其他内容。我想,在子列表上调用
clear()
可以处理您的工作。但它可能正在使用 在后台迭代,我不确定。供您使用的示例脚本:# 6 楼答案
创建^{}
检查此方法的实现,并进行一些测试以确定性能