簡體   English   中英

如何在對列表執行某些操作后刪除列表的最后一個 x 元素?

[英]How to delete last x element of a list after performing some operation on them?

我知道如何使用以下方法迭代列表的最后 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 

如果您需要從集合中刪除元素(在您的情況下為 List),請使用 Iterator 而不是索引for循環。 請參閱使用迭代器從列表中刪除條目

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM