aspose file tools*
The moose likes Beginning Java and the fly likes My LinkedList Iterator - Can't print first element - No use of Java API Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "My LinkedList Iterator - Can Watch "My LinkedList Iterator - Can New topic
Author

My LinkedList Iterator - Can't print first element - No use of Java API

Dante Hawke
Greenhorn

Joined: Jan 27, 2009
Posts: 7
Hello all,

I am currently trying to create my own Iterator for my own LinkedList class as part of a task, it's implementation must mirror that of the Java API LinkedList.

My BasicLinkedList works fine, however I have become a bit stuck working on its anonymous Iterator class, that should have a hasNext(), next() and remove() method.
At the moment it can hasNext() and print out the next() of all items in the list except for the first.

Here is my code.

BasicLinkedList:



Anonymous Iterator Class:




Inner Node Class:




Any help is appreciated, many thanks!

Cheers.
Lorand Komaromi
Ranch Hand

Joined: Oct 08, 2009
Posts: 276
Dante Hawke wrote:private Node current = header;


You have to make sure that the first call to next() will return the first Node in the List. You could achieve this by setting current to a new Node instance whose next you would set to head...


OCJP 6 (93%)
Dante Hawke
Greenhorn

Joined: Jan 27, 2009
Posts: 7
Many thanks, that solved that problem, but now it doesn't print the last one in the LinkedList, I'm completely stumped here!


Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
Are you sure about current.setNext(current.getNext())? Does that really remove the item?
Dante Hawke
Greenhorn

Joined: Jan 27, 2009
Posts: 7
My hasNext() and next() method appear to work perfectly now under a few simple tests, my refined Iterator is as follows:

My current remove method is:


However, with some testing I have found that the remove method will always fail to remove the first Node.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
That looks better, though I haven't gone through it carefully
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: My LinkedList Iterator - Can't print first element - No use of Java API