2012-07-09 117 views
0

以下是我的學習目標。我已經開始了,但我真的不知道該從哪裏開始執行主程序。我將不勝感激任何幫助!將迭代器添加到集合中

目的:

  • 通過創建一個私有的內部類添加一個Iterator對象的採集卡
  • 迭代器被添加到收藏。
  • 您可以使用任何適當的內部類類型
  • 枚舉器和迭代器使用大量數據來確定集合何時更改。
  • 實現正確的方法,接口併爲與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); 
    } 
    
    } 
    
+3

這是非常,非常不尋常 - 可能不是你的意思 - 有一類'Foo'實現的Iterable''。你應該確保你跟蹤哪些東西應該是多個'Foo',哪個應該是一個'Foo'。 – 2012-07-09 20:36:02

回答

2

你有兩個概念,我認爲你可能混在一起。如果可迭代某些內部元素,則該對象爲Iterable。

所以,如果我有一個物品在其中的購物車,我可以迭代我的雜貨。

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

所以爲了使用這個功能,我需要提供一個Iterator。在你的代碼示例中,你正在重用ArrayList中的迭代器。從你的練習描述中,我相信你需要自己實現一個。例如:

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 
} 

所以我給你一個提示構造函數/成員變量。在你創建這個類後,你的Iterable類(我的ShoppingCart)將返回我的新迭代器。

該分配建議爲您的自定義迭代器使用私有內部類。

好運

1
  • 可迭代對象通常是集合。 CardCollection比Card更適合
  • 公共方法cards()和notes()返回類型Card和Note,它們是私有的。我認爲這些意圖是公開的。
  • 我覺得方法cards()和notes()是爲了返回迭代器。