开发者

Which is the best way to iterate over a non-generic List? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific mome开发者_如何学编程nt in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 11 years ago.

I have to use an old piece of code where I have a List and I need to iterate over it. Foreach loop does not work. Which is the best and safest way to do this?

Example

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


Use Iterator:

Iterator iter = objects.iterator();
while (iter.hasNext()) {
    Object element = iter.next();
}

Or better directly for-each:

for (Object obj : objects) {
}


Either use an iterator, if you need to be able to remove the current element from the list:

for (Iterator it = list.iterator(); it.hasNext();) {
    Foo foo = (Foo) it.next();
    // ...
    it.remove();
}

Or use a foreach loop:

for (Object o : list) {
    Foo foo = (Foo) o;
    // ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜