JDK内置的迭代器(List/Set)
package com.qianyu.gof.iterator;
import java.util.ArrayList;
import java.util.Iterator;
/**
- @author lijing
- @date 2019-04-10-14:38
- @discroption JDK内置迭代器测试类
*/
public class IteratorTest {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add(“a”);
list.add(“b”);
list.add(“c”);
Iterator iter = list.iterator();
//hasNext()判断是否有下一个元素
while (iter.hasNext()) {
//next()函数返回当前元素,并将游标指向下一位
System.out.println(iter.next());
}
}
}
手动实现迭代器
package com.qianyu.gof.iterator;
/**
-
@author lijing
-
@date 2019-04-10-14:37
-
@discroption 迭代器接口
/
public interface MyIterator {
/*- 判断是否有下一个元素
- @return
*/
boolean hasNext();
/**
- 返回当前元素,并且将游标向下移动一位
- @return
*/
Object next();
}
package com.qianyu.gof.iterator;
import java.util.ArrayList;
import java.util.List;
/**
-
@author lijing
-
@date 2019-04-10-19:18
-
@discroption 自定义聚合类
*/
public class MyList {
List list = new ArrayList();public boolean add(Object obj) {
return list.add(obj);
}public boolean remove(Object obj) {
return list.remove(obj);
}/**
- 返回迭代器对象
- @return
*/
public ConcreteIterator iterator() {
return new ConcreteIterator();
}
/**
-
自定义内部类,可以直接使用外部类的属性
*/
private class ConcreteIterator implements MyIterator {
//游标
private int cursor = 0;@Override
public boolean hasNext() {
return this.cursor < list.size();
}@Override
public Object next() {
return list.get(cursor++);
}
}
}
package com.qianyu.gof.iterator;
/**
- @author lijing
- @date 2019-04-10-19:14
- @discroption 自定义迭代器测试类(迭代器模式)
*/
public class IteratorTest2 {
public static void main(String[] args) {
MyList myList = new MyList();
myList.add(“aa”);
myList.add(“bb”);
myList.add(“cc”);
MyIterator iter = myList.iterator();
while (iter.hasNext()){
System.out.println(iter.next());
}
}
}