简体   繁体   English

用Java制作自己的收藏集的正确方法

[英]Right way to make my own collection in java

I'm trying to do my own collection class in java. 我正在尝试在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. 因为我不知道是否封装哈希表和arraylist并实现足够的基本操作来调用此类的“集合”。

I will be very thankful for any advice or correction of this code. 对于该代码的任何建议或更正,我将非常感谢。

Thanks. 谢谢。

i think the best way to do this is implementing Collection 我认为最好的方法是实施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() 这样,您必须在collection接口中实现每个方法bt,使您的类扩展AbstractCollection extends AbstractCollection非常容易,因为它为我们完成了所有必要的工作,而您唯一需要担心的是iterator()size()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM