Tin Le
Tin Le

Reputation: 53

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

Upvotes: 5

Views: 94

Answers (2)

Mario Rossi
Mario Rossi

Reputation: 7799

In the first case you are creating a new Iterator (which starts with the first element again and again) every time you check the condition in the loop. And then you create more of them in the println (2 iterators created per loop). The program displays the first element ("yo") endlessly.

Upvotes: 0

nanofarad
nanofarad

Reputation: 41281

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.

Upvotes: 6

Related Questions