plasticfood 0 Junior Poster in Training

ok i have this assignment which i'm just having problems with the iterator part of it.

from the ListType class, this is what i wrote:

public Iterator iterator(){
		return new OrderedStringListTypeIterator(list);
	}

this code is from the textbook which idk how they got theirs to work, but...

import java.util.Iterator;
import java.util.NoSuchElementException;


public class OrderedStringListTypeIterator implements Iterator
{  
   private String[] list;  
   private int previous;        
   boolean canRemove;            
   
  
   public OrderedStringListTypeIterator(String [] aList)
   {
     
      list = aList;
     
      previous = -1;
   
      canRemove = false;
   }
   
   
   public boolean hasNext()
   {
      
      if ((previous + 1) < list.size())
         return true;
      else
         return false;
   }
   
   
   public String next()
   {
      
      if (!hasNext())
         throw new NoSuchElementException();
      
      
      previous++;
      
      
      canRemove = true;
      
      
      return list.get(previous);
   }
   
 
   public void remove()  
   {
     
      if (!canRemove)
         throw new IllegalStateException();
         
     
      list.remove(previous);
      
      
      previous--;
      
      
      canRemove = false;
   }
}

i'm getting error from the list.size() command, and i do know why, but this is the code from the book and i'm supposed to use it. am i supposed to create an ListType object in the OrderedStringListTypeIterator constructor in order to access its methods, or do i extend ListType instead? i've tried extending, but when testing it out in the driver class, it keeps telling me that it doesn't have a next element. so basically my list is empty which it shouldn't be. i'm so confused, and i don't really understand the point of an iterator.

i've done further testing and the size() method is always return 0, have no idea why.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.