迭代非泛型列表的最佳方法是哪种?

时间:2011-09-16 14:04:21

标签: java loops iteration raw-types

我必须使用一段旧代码,我有一个List,我需要迭代它。 Foreach循环不起作用。哪种方法最好,最安全?

实施例

private void process(List objects) {
    someloop {
        //do something with list item
        //lets assume objects in the List are instances of Content class
    }           
}

2 个答案:

答案 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;
    // ...
}