I am practicing list iteration then I got stuck. My question is, why do these two methods give different results.
The first code prints out a infinite loop. While the second, prints out the next String in the index.
I am new to java, this is also my first language.
public static void main(String[] args) {
String[] hi = {"yo", "wat", "sup"};
List<String> l1 = new ArrayList(Arrays.asList(hi));
while (l1.iterator().hasNext()) {
System.out.println(l1.iterator().next());
;
}
}
public static void main(String[] args) {
String[] hi = {"yo", "wat", "sup"};
List<String> l1 = new ArrayList(Arrays.asList(hi));
Iterator<String> rator = l1.iterator();
while (rator.hasNext()) {
System.out.println(rator.next());
}
}
The primary purpose of an iterator is to allow a user to process every element of a container while isolating the user from the internal structure of the container. This allows the container to store elements in any manner it wishes while allowing the user to treat it as if it were a simple sequence or list.
That being said, the iterators from itertools are often significantly faster than regular iteration from a standard Python for loop.
Benefits of Iterators. Use of an iterator simplifies the code and makes it general. Benefits of using this iterator API include: treats variables of all types, sizes, and shapes uniformly, whether they fit in memory or not, even if a single row won't fit in memory.
An iterator is an object (like a pointer) that points to an element inside the container. We can use iterators to move through the contents of the container. They can be visualised as something similar to a pointer pointing to some location and we can access content at that particular location using them.
l1.iterator(
always generates a new iterator. In the first piece of code you're creating a new iterator, discarding it, recreating it, and discarding it again. Since the iterator doesn't get a chance to reach the end, you'll never exit the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With