wessltov
wessltov

Reputation: 67

for in loop or iterator?

I work in Netbeans, and it keeps advising me to use an iterator rather than a for-in loop. Last time I encountered it was with this bit:

ArrayList<String> numString = new ArrayList<>();
ArrayList<Integer> nums = new ArrayList<>();

String allNums = "";

nums.add(1);
nums.add(2);
nums.add(9);

for(int num : nums) {

    allNums += String.valueOf(num);
}
numString.add(allNums);

for(String num : numString) {

    System.out.println(num);
}

Does it have to do with efficiency? Via my own logic, the example above it more efficent than importing a class.

Upvotes: 3

Views: 146

Answers (3)

Tom C
Tom C

Reputation: 814

A for loop like the following is basically a pretty looking iterator that was designed to iterate over the collection.

It doesn't really matter unless you are doing other things that require you to remove elements, the ability to move forward next() or backwards previous() through the list, and the ability to check for more elements by using hasNext()

TL:DR Its better to use a forEach loop if you just want to iterate over the Collection. Otherwise, use a iterator.

Upvotes: 1

Andy Turner
Andy Turner

Reputation: 140319

The enhanced for statement is syntactic sugar to make it nicer to iterate through an Iterable. Referring to the JLS:

The enhanced for statement has the form:

EnhancedForStatement:
     for ( FormalParameter : Expression ) Statement

...

The enhanced for statement is equivalent to a basic for statement of the form:

for (I #i = Expression.iterator(); #i.hasNext(); ) {
    VariableModifiersopt TargetType Identifier =
         (TargetType) #i.next();
    Statement
}

So writing an enhanced for statement cannot be more efficient than using an explicit iterator, since it is implemented using an iterator.

It seems surprising that a Netbeans would advise use of the explicit iterator form for the code you have given in your question - whilst the existence of a language feature does not necessarily imply that it is a good idea to use it, I can't see what advantage not using it would give in this case.

Upvotes: 0

mlewandowski
mlewandowski

Reputation: 802

Try to use for loop and remove some element while looping over :-) You will get pretty exception ConcurrentModificationException and that's why using Iterator interface is safe and may be used in such situation. I assume it's probable cause of NetBeans advising you to use Iterator.

Upvotes: 1

Related Questions