문제

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;
    // ...
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top