Ank*_*kur 31 java iteration reverse arraylist
当我反复遍历ArrayList时,我得到一个IndexOutOfBoundsException.我尝试进行前向迭代,没有问题.我希望并知道列表中有五个元素.代码如下:
Collection rtns = absRtnMap.values();
List list = new ArrayList(rtns);
Collections.sort(list);
for(int j=list.size();j>0;j=j-1){
System.out.println(list.get(j));
}
Run Code Online (Sandbox Code Playgroud)
前向迭代 - 工作正常,但对我没用:
for(int j=0;j<list.size();j++){
System.out.println(list.isEmpty());
System.out.println(list.get(j));
} // this worked fine
Run Code Online (Sandbox Code Playgroud)
错误:
Exception in thread "Timer-0" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
at java.util.ArrayList.RangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at model.Return.getReturnMap(Return.java:61)
at controller.Poller$1.run(Poller.java:29)
at java.util.TimerThread.mainLoop(Unknown Source)
at java.util.TimerThread.run(Unknown Source)
Run Code Online (Sandbox Code Playgroud)
此外,如果有人知道反向迭代更好的习语,我很乐意尝试这一点.
Sua*_*ehi 87
完全避免索引?怎么样:
for (ListIterator iterator = list.listIterator(list.size()); iterator.hasPrevious();) {
final Object listElement = iterator.previous();
}
Run Code Online (Sandbox Code Playgroud)
Dav*_*d Z 63
开始迭代,list.size() - 1
因为数组(或ArrayList
)元素的编号从0到1小于列表的大小.这是一个相当标准的习语:
for (int j = list.size() - 1; j >= 0; j--) {
// whatever
}
Run Code Online (Sandbox Code Playgroud)
请注意,您的前向迭代有效,因为它在到达之前停止list.size()
.
Sna*_*ler 28
我知道这是一个老问题,但Java包含一个Collections.reverse( List<T> )
方法.你为什么不反转它并进行前向迭代?
el *_*ego 12
最优雅的方法是反转数组,然后使用直接(甚至隐式)迭代器:
Collections.reverse(arrayList);
for (Object item : arrayList) {
...
}
Run Code Online (Sandbox Code Playgroud)
Cli*_*int 11
list.size()超过了最后一个允许的索引.
for(int j = list.size() - 1; j >= 0; j--) {
System.out.println(list.get(j));
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
70098 次 |
最近记录: |