0
Possibilitys to iterate
Why does this not work? import java.util.Iterator; import java.util.LinkedList; public class MyClass { public static void main(String[ ] args) { LinkedList<String> animals = new LinkedList<String>(); animals.add("fox"); animals.add("cat"); animals.add("dog"); animals.add("rabbit"); for(int i=0; i<5; i++){ Iterator<String> it = animals.iterator(); String value = it.next(); System.out.println(value); } } } Reust is 5 times fox. But I want to iterate all values. Thanks!
13 ответов
+ 1
iterator has hasNext() method which return boolean true if it has value to iterate..
u can use that in while loop condition
+ 1
You shloud write, assigning Iterator before the loop...
And you have only 4 elements added so use i<4 or size() method return size of list...
Iterator<String> it = animals.iterator();
for(int i=0; i< 4; i++){ //or use i<animals.size();
String value = it.next();
System.out.println(value);}
Edit:
Simple way,..!
if just to display, not need to iterate :
System.out.println(animals) ;
+ 1
Simple way:
for(String animal : animals) {
System.out.println(animal);
}
Less simple: You can use an iterator. But then you have to loop while it has a next element, like Lily mentioned. Currently you do only access five times the first element.
+ 1
Iterator<String> it = animals.iterator();
// for(int i=0; i<5; i++){
for(int i=0; i<4; i++) {
// Iterator<String> it = animals.iterator();
String value = it.next();
System.out.println(value);
}
+ 1
Sandra Meyer why? Maybe sometimes you don't have to iterate whole collection?
0
Iterating based on the length is acceptable for sololearn, but not for real projects.
0
Then I would prefer a stop condition. Iterating on the previously requested length is only secure if you are sure, that nobody and nothing could access the list in the meantime. This is usually given here, but not based on my project experience.
0
Sandra Meyer then you should use immutable collections if you worry about collection to be changed.
0
Could be a valid change, e.g. insertions. It's just not good style to use a counter, unnecessary additional variables and loop less secure where 2 clean valid implementations are given.
0
Sandra Meyer if there insertions happens, then size() method also returns changed size.. Is not it..?
0
The size is only requested once with starting the loop. There are reasons why the for-each loop is called the enhanced for-loop. Iterator is another possibility but in fact not required here, because it is determined for completely other use cases.
https://www.programiz.com/java-programming/enhanced-for-loop
0
And here a quite useful explanation what iterator is used for:
http://www.javapractices.com/topic/TopicAction.do?Id=125
0
Thank you guys!