2016-04-25 40 views
0

我試圖在java中完成自己的集合類。在java中創建我自己的集合的正確方法

我需要通過鍵找到數據,並且能夠遍歷它並通過索引獲取元素,所以我決定對散列表和數組列表進行封裝。

這是我的代碼:

public class GeoCollection <T extends Geographic> implements Iterable<T>, Iterator<T>{ 

private Hashtable<String,T> data_table; 
private ArrayList<T> data; 
private int cursor = 0; 

public GeoCollection(){ 
    data = new ArrayList<>(); 
    data_table = new Hashtable<>(); 
} 

public void add(String key,T data){ 
    this.data.add(data); 
    data_table.put(key,data); 
} 

public T get(int index){ 
    if(index >= data.size()) 
     throw new IndexOutOfBoundsException(); 
    return data.get(index); 
} 

public T get(String v){ 
    return data_table.get(v); 
} 

public T next() { 
    if(cursor == data.size()) 
     throw new NoSuchElementException(); 
    cursor++; 
    return data.get(cursor-1); 
} 

public T first(){ 
    cursor = 0; 
    return data.get(cursor); 
} 
public boolean hasNext(){ 
    return cursor < data.size(); 
} 

public boolean remove(Person p) { 
    return data.remove(p); 
} 

//se implemeta el iterator 
@Override 
public Iterator<T> iterator() { 
    cursor = 0; 
    return this; 
} 

}

有任何需要實現列表接口或類似的東西?因爲我不知道是否將hashtable和arraylist封裝起來,並且足夠執行基本操作來調用「Collection」這個類。

對於此代碼的任何建議或更正,我將非常感謝。

謝謝。

+0

爲什麼不實現'Collection'接口? – Logan

+3

這更可能是[代碼評論](http://codereview.stackexchange.com)上的主題。 – Radiodef

+0

你不能實現'List'(至少不是關於添加的部分),因爲List條目沒有鍵。你可能想要實現'Map'。 – Thilo

回答

1

我認爲要做到這一點,最好的辦法是實現收集

implements java.util.Collection<E> 

這樣,你必須實現Collection接口的每一個方法BT 使得擴展類AbstractCollectionextends AbstractCollection得多容易因爲它確實爲 對我們來說所有必需的東西,你唯一擔心的是 iterator()size()

相關問題