Iterator can be retrieved In most cases, the owner is Iterable, so it is possible to loop with an extended for statement without using Iterator (code below). This time, instead of using the extended for statement, I dare to use Iterator to run the loop. Thank you for your cooperation.
List is Iterable, so you can dig into an extended for statement
//List object to retrieve elements one by one
List<String> list = Arrays.asList("a", "i", "u", "e", "o");
//It seems that you can turn the loop by using something called Iterator, so take it out
Iterator<String> iterator = list.iterator();
//That being said, List is Iterable, so you can dig into an extended for statement.
for(String str : list){
System.out.println(str);
}
//The iterator has been dismissed(Crying)
iterator = null;
Method | function |
---|---|
T next() | Extract the next element |
boolean hasNext() | Seen from the current state, true is returned if the next element can be retrieved. |
Iterator is an interface for tracing elements in sequence.
You can retrieve the element by calling the next ()
method.
The general usage is "continue to callnext ()
only whilehasNext ()
returns true".
Iterator has an internal state, and each time you retrieve an element using next ()
, its internal state changes. (Finally, hasNext ()
will return false)
It is a ** disposable premise ** interface because there are no defined methods to undo or return to the initial state.
(I don't think so) Please be careful when you make your own Iterator.
The introduction has become long, but it is a code. There are two types, a while statement and a for statement.
Iterator<String> itr = list.iterator();
while(itr.hasNext()){
String str = itr.next();
System.out.println(str);
}
for(Iterator<String> itr = list.iterator(); itr.hasNext();){
String str = itr.next();
System.out.println(str);
}
Personally, I prefer the for statement, which narrows the scope of variables.
Recommended Posts