3

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.

2
  • Note that allNums += would be better implemented using a StringBuilder - but that's somewhat orthogonal to the question. Commented Mar 7, 2016 at 10:15
  • You might want to take a look at stackoverflow.com/questions/1879255/… Commented Mar 7, 2016 at 10:16

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.