user1077685
user1077685

Reputation:

Adding an Iterator to a Collection

Below is my learning objective. I got it started, but I don't really know where to go from here to implement the program in main. I would appreciate any help!

Objective:

Upvotes: 0

Views: 321

Answers (2)

jeff
jeff

Reputation: 4333

You have two concepts here that I think you may be mixing up. An object if Iterable if you can iterate over some internal elements.

So if I have a shopping cart with items in it, I can iterate over my groceries.

public class ShoppingCart implements Iterable<GroceryItem>
{
   public Iterator<GroceryItem> iterator()
   {
      // return an iterator
   }
}

So in order to use this functionality, I need to provide an Iterator. In your code example, you are reusing the iterators from ArrayList. From your exercise description, I believe you need to implement one yourself. For example:

public class GroceryIterator implements Iterator<GroceryItem>
{
  private GroceryItem[] items;
  private int currentElement = 0;

  public GroceryIterator(GroceryItem[] items)
  {
    this.items = items;
  }

  public GroceryItem next() // implement this
  public void remove() // implement this
  public boolean hasNext() // implement this
}

So I sorta gave you a hint with the constructor/member variables. After you make this class, your Iterable class (my ShoppingCart) will return my new iterator.

The assignment recommends using a private inner class for your custom Iterator.

Good luck

Upvotes: 2

Javier
Javier

Reputation: 678

  • Iterable objects are usually collections. That suits better with CardCollection than with Card
  • Public methods cards() and notes() are returning types Card and Note which are private. I think those are meant to be public.
  • I think methods cards() and notes() are meant to return the iterator.

Upvotes: 1

Related Questions