迭代器

第一次进行数据结构的系统学习,首先这篇文章主要是依据 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)   这个方法的应用我之前并不会,值得学习

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值