这是迭代非泛型List的最佳方法



我必须使用一段旧代码,我有一个列表,我需要迭代它。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;
    // ...
}

相关内容

最新更新