0
  public boolean hasNext() {
          // TODO Auto-generated method stub
          return current != null;
      }


      public T next() throws NoSuchElementException {

          if (!hasNext())
              throw new NoSuchElementException();
          else  
              prev = current;
          current = current.next;


          return (T) prev.data;
      }

  //This is my linked list
 f.add(132);
  f.add(133);

//while loop I am using in regular main method to test
 while(f.iterator().hasNext()){
System.out.println(f.iterator().next());
 }

For some reason I just get an infinite loop here and I am not sure why. I ran this in my main method and it just kept printing 132, I am not sure what's wrong.

1
  • Can you also add your code for Linked List and how you are creating iterator to get more clarity? Commented Mar 13, 2014 at 4:36

2 Answers 2

1

Get the iterator out of the loop. You are getting a new iterator every time the loop completes one circle. Thus just the first element is printed again and again.

Sign up to request clarification or add additional context in comments.

Comments

0

Since the same element print again and again, there are 2 possibility could be happen.

  1. The iterator is not moving and pointed to same element, even after you call next.
  2. The linked-list is a circular one, iterator is automatically moving without call next. So iterator move to next Node (value = 133) and then calling next will move it to same element, since it is circular one.

I hope the problem is with the linked-list code. So give the linked-list code. It will help to find out the bug.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.