我必须使用一段旧代码,我有一个列表,我需要迭代它。Foreach循环不起作用。哪种方法最好、最安全?
例子private void process(List objects) {
someloop {
//do something with list item
//lets assume objects in the List are instances of Content class
}
}
使用Iterator
:
Iterator iter = objects.iterator();
while (iter.hasNext()) {
Object element = iter.next();
}
或者最好直接for-each:
for (Object obj : objects) {
}
如果需要从列表中删除当前元素,可以使用迭代器:
for (Iterator it = list.iterator(); it.hasNext();) {
Foo foo = (Foo) it.next();
// ...
it.remove();
}
或者使用foreach循环:
for (Object o : list) {
Foo foo = (Foo) o;
// ...
}