Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 554
wessltov Avatar asked Feb 07 '26 18:02

wessltov


2 Answers

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.

like image 110
Tom C Avatar answered Feb 09 '26 10:02

Tom C


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.

like image 34
mlewandowski Avatar answered Feb 09 '26 08:02

mlewandowski