user2059856
user2059856

Reputation: 5

Implenting Iterator interface in a linked list class

  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.

Upvotes: 0

Views: 51

Answers (2)

Banukobhan Nagendram
Banukobhan Nagendram

Reputation: 2597

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.

Upvotes: 0

Hirak
Hirak

Reputation: 3649

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.

Upvotes: 1

Related Questions