Reputation:
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:
Implement the correct methods, interfaces, and extend the appropriate classes for a class consistent with the Java API.
public class CardCollection {
private ArrayList<Card> cards;
private ArrayList<Note> notes;
public CardCollection() { //constructor initializes the two arraylists
cards = new ArrayList<Card>();
notes = new ArrayList<Note>();
}
private class Card implements Iterable<Card> { //create the inner class
public Iterator<Card> iterator() { //create the Iterator for Card
return cards.iterator();
}
}
private class Note implements Iterable<Note> { //create the inner class
public Iterator<Note> iterator() { //create the Iterator for Note
return notes.iterator();
}
}
public Card cards() {
return new Card();
}
public Note notes() {
return new Note();
}
public void add(Card card) {
cards.add(card);
}
public void add(Note note) {
notes.add(note);
}
}
Upvotes: 0
Views: 321
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
Reputation: 678
Upvotes: 1