views:

152

answers:

2

I created my list:

private static List list = new LinkedList();

and my iterator:

ListIterator itr = list.listIterator();

and use this code to try to print out the list... Only problem is, it never comes out of the loop. When it reaches the tail, shouldn't it come out of the loop, because there is no next? Or is it going back to the head like a circular linked list? It is printing so quickly and my computer locks up shortly after, so I can't really tell what is going on.

while (itr.hasNext())
    System.out.println(itr.next());
+1  A: 

From what little you've shown there is no way for us to deduce where your troubles lie.

private static List list = new LinkedList();

public Foo(){
    ListIterator itr = list.listIterator();
    while( itr.hasNext() ){
        System.out.println( iter.next() );
    }
}

Instead, we're forced to guess. Here's my stab:

  1. You've got a static List object shared amongst any number of threads without any perceivable thread safety mechanism. Somehow you're adding new items within another running thread as you're looping through the while loop .
  2. Following those lines there's a bit of code you're not showing us within the while-loop wherein another item is appended to the end of the list.
  3. There's another function which does a lot of work and/or builds up a lot of unreleasable memory, thereby causing your computer's performance to take a nosedive.

I'll add more when I think of them ...or you can post more code to give us a better idea of what's going on. I'd suggest any code which might be interacting with that List object.

wheaties
A: 

To stop the infinite loop, add a safety check and see what gets printed to help see what the problem is:

private static List list = new LinkedList();

ListIterator itr = list.listIterator();

int len = list.size();

while (0 < len-- && itr.hasNext()) {
    System.out.println(itr.next());
}

Can you reproduce the problem using a non-static list too?

(btw, wild guess, you could get the behaviour you describe by creating a new iterator everytime through the loop, like list.listIterator().hasNext, list.listIterator().next)

rsp