迭代器

来源:互联网 发布:plsql导出表数据 编辑:程序博客网 时间:2024/05/01 08:23

第一次进行数据结构的系统学习,首先这篇文章主要是依据 http://blog.csdn.net/jjwwmlp456/article/details/39992057。

首先我自己理解一下迭代器这个东西,它是一个对集合进行增删改查判断等一系列功能的一个工具,注意这里是工具,所以对于集合的内部结构是相对封闭的。

这边我用了两个接口。一个是集合类的接口,一个是迭代器的接口。

public interface ICollection<T> {  //集合类接口
    IIterator<T> iterator(); //创建集合迭代器的函数
    void add(T t);
    T get(int index);
}

public interface IIterator<T> { //迭代器接口
    boolean hasNext();
    boolean hasPrevious();
    T next();
    T previous();
}


public class MyCollection<T> implements ICollection<T>{  //集合类
    private T[] arys;  //定义集合(这里的集合数据结构为数组)
    private int index=-1; //集合起始下标
    private int capacity=5; //集合容量
    
    public MyCollection(){
    this.arys=(T[])new Object[capacity];
    }
@Override
public IIterator iterator() {

return new MyIterator<T>(this);
}


@Override
public T get(int index) {
return this.arys[index];
}


@SuppressWarnings("unchecked")
@Override
public void add(Object t) {
index++;
if(index==capacity){
capacity*=2;
this.arys=Arrays.copyOf(arys,capacity);
}
this.arys[index]=(T) t;

}
}


public class MyIterator<T>  implements IIterator<T>  {  //迭代器类
    private MyCollection collection;
    private int index=0;
    
public MyIterator(MyCollection<T> myCollection) {
this.collection=new MyCollection();
this.collection=myCollection;

}
@Override
public boolean hasNext() {
if(collection.get(index+1)!=null) return true;
return false;
}


@Override
public boolean hasPrevious() {
if(collection.get(index-1)!=null)
return false;
return true;
}


@Override
public T next() {
return (T) collection.get(index++);
}


@Override
public T previous() {
return (T) collection.get(index--);
}
}


public class Vector {//测试的主函数
    public static void main(String[] args){
    ICollection<Integer> collection =new MyCollection<Integer>();
    add(collection, 3, 5, 8, 12, 3, 3, 5);  
    for (IIterator<Integer> iterator = collection.iterator(); iterator.hasNext();) {  
            System.out.println(iterator.next());  
        }  
    ICollection collection2 = new MyCollection();  
        add(collection2, "a", "b", "c", 3, 8, 12, 3, 5);  
        for (IIterator iterator = collection2.iterator(); iterator.hasNext();) {  
            System.out.println(iterator.next());  
        }  
    }


    static <T> void  add(ICollection<T> c, T ...a) {  
        for (T i : a) {  
            c.add(i);  
        }  
    }  
}


结果:

3
5
8
12
3
3
a
b
c
3
8
12
3


反思:我这边其实还有很多问题,比如说这个<T>的使用我一直觉得蛮奇怪的,比如 static <T> void  add(ICollection<T> c, T ...a)   这个方法的应用我之前并不会,值得学习

0 0
原创粉丝点击