Reputation: 1823
I'm trying to do my own collection class in java.
I need to find data by a key and also be able to iterate on it and get a element by his index, so i decide to make an encapsulation of the hashtable and the arraylist.
This is my code:
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;
}
}
There's any need to implement list interface or something like that? Because i don't know if encapsulating the hashtable and the arraylist and implementing the basic operations in enough to call "Collection" this class.
I will be very thankful for any advice or correction of this code.
Thanks.
Upvotes: 0
Views: 129
Reputation: 2969
i think the best way to do this is implementing Collection
implements java.util.Collection<E>
that way you have to implement every method in the collection interface bt
making your class extending AbstractCollection extends AbstractCollection
is much more easy since it does
all the nessessary things for us and only thing you have to worry about is
iterator()
and size()
Upvotes: 1