Tuesday, February 19, 2013

Iterating over List elements

The common way to iterate over List elements:

List list;
for (int i = 0; i < list.size(); i++) {
    doSomething(list.get(i));
}

The correct way to iterate polymorphic List is via Iterator or for-each loop:

List list;
for (Iterator it = list.iterator(); it.hasNext(); ) {
    doSomething(it.next());
}

// for each
for (E elem : list) {
    doSomething(elem);

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...

Blog List