我必须使用一段旧代码,我有一个List,我需要迭代它。 Foreach循环不起作用。哪种方法最好,最安全?
实施例
private void process(List objects) {
someloop {
//do something with list item
//lets assume objects in the List are instances of Content class
}
}
答案 0 :(得分:8)
使用Iterator
:
Iterator iter = objects.iterator();
while (iter.hasNext()) {
Object element = iter.next();
}
或者更直接地为每个人:
for (Object obj : objects) {
}
答案 1 :(得分:3)
如果您需要能够从列表中删除当前元素,请使用迭代器:
for (Iterator it = list.iterator(); it.hasNext();) {
Foo foo = (Foo) it.next();
// ...
it.remove();
}
或使用foreach循环:
for (Object o : list) {
Foo foo = (Foo) o;
// ...
}