[英]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.