Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do these two list Iterators behave differently?

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());
        ;
    }
   }

VS

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());
    }
}
like image 271
Tin Le Avatar asked Sep 01 '13 07:09

Tin Le


People also ask

What is an iterator and why are iterators necessary?

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.

Are iterators faster than for loops python?

That being said, the iterators from itertools are often significantly faster than regular iteration from a standard Python for loop.

What is the advantage of iterators?

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.

What does iterator do in C++?

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.


1 Answers

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.

like image 123
nanofarad Avatar answered Sep 27 '22 21:09

nanofarad