簡體   English   中英

Java反轉for循環中訪問列表的順序

[英]Java reverse the order of accessing a list in a for loop

我想反轉在for()中訪問列表的順序

這是我的實際代碼

for(int i = 0; i < states.size(); i++) {
    System.out.println(states.size());
    states.get(i).update(true); // restore the first blockstate
    states.remove(i); // remove the first blockstate from the list
}

此代碼有效,但我想將其反轉。 我已經嘗試了其他方式,例如使用i--但沒有用。 有人可以提供建議嗎?

我已經嘗試了其他方式,例如使用i--但沒有用。

反轉for循環包括三個步驟:

  • 將初始值更改為最后一個值,
  • 更改條件以通過初始值后停止
  • 反轉增量/減量(即++變為--

在您的代碼中,此更改如下所示:

for(int i = states.size()-1 ; i >= 0 ; i--) {
    System.out.println(states.size());
    states.get(i).update(true); // restore the current blockstate
    states.remove(i); // remove the current blockstate from the list
}

注意,在原始循環中到達的最后一個值是states.size()-1 ,而不是states.size() ,因此i需要從states.size()-1開始。

由於您的循環最終還是會清除該列表,但一次只清除一個元素,因此可以通過刪除remove(i)調用,並在循環后將它替換為states.clear()來獲得更好的清晰度。

for(int i = states.size()-1 ; i >= 0 ; i--) {
    System.out.println(states.size());
    states.get(i).update(true); // restore the current blockstate
}
states.clear();

嘗試這個:

List list = Lists.reverse(states); 
for(int i = 0; i < list.size(); i++) {
    System.out.println(list.size());
    list.get(i).update(true); // restore the first blockstate
    //list.remove(i); // remove the first blockstate from the list
 }

如果您要在訪問元素時刪除元素,則必須使用簡單的迭代器,因為這是不可能的...它引發並發修改異常

暫無
暫無

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

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