我知道如何使用以下方法迭代列表的最后 n 个元素:
for(int i = list.size()-1; i>elements ; i --)
{
list.element.get(i).makeSomeStuff();
list.remove(list.element.get(i));
}
但我需要安全地从列表中删除元素而不会弄乱索引
这个想法是创建一个辅助列表来保存要从原始列表中删除的对象。
List<MyObject> toBeRemovedList = new ArrayList()<>;
for(int i = list.size()-1; i>elements ; i --)
{
MyObject myObject = list.get(i);
myObject.makeSomeStuff(); //perform object action
toBeRemovedList.add(myObject); //add the object into the removal list
}
list.removeAll(toBeRemovedList); //remove all the elements of the removal list from the originating list, no index interfering
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句