java 实现 iterator_Java 实现迭代器(Iterator)模式

类图

63304238eaebf454355dc95ae502f09e.png

/**

* 自己定义集合接口, 相似java.util.Collection

* 用于数据存储

* @author stone

*

*/

public interface ICollection {

IIterator iterator(); //返回迭代器

void add(T t);

T get(int index);

}

/**

* 自己定义迭代器接口 相似于java.util.Iterator

* 用于遍历集合类ICollection的数据

* @author stone

*

*/

public interface IIterator {

boolean hasNext();

boolean hasPrevious();

T next();

T previous();

}

/**

* 集合类, 依赖于MyIterator

* @author stone

*/

public class MyCollection implements ICollection {

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(this);

}

@Override

public void add(T t) {

index++;

if (index == capacity) {

capacity *= 2;

this.arys = Arrays.copyOf(arys, capacity);

}

this.arys[index] = t;

}

@Override

public T get(int index) {

return this.arys[index];

}

}

/*

* 迭代器(Iterator)模式 又叫做游标(Cursor)模式

* 提供一种方法訪问一个容器(container)对象中各个元素,而又不需暴露该对象的内部细节。

* Iterator模式就是分离了集合对象的遍历行为,抽象出一个迭代器类来负责,这样既能够做到不暴露集合的内部结构,又可让外部代码透明的訪问集合内部的数据

*

* 若有新的存储结构,可new 一个ICollection, 相应的 new 一个IIterator来实现它的遍历

*/

@SuppressWarnings({"rawtypes", "unchecked"})

public class Test {

public static void main(String[] args) {

ICollection collection = new MyCollection();

add(collection, 3, 5, 8, 12, 3, 3, 5);

for (IIterator iterator = collection.iterator(); iterator.hasNext();) {

System.out.println(iterator.next());

}

System.out.println("-------------");

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 void add(ICollection c, T ...a) {

for (T i : a) {

c.add(i);

}

}

}

打印

3

5

8

12

3

3

5

-------------

a

b

c

3

8

12

3

5

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值