## 编程知识 cdmana.com

### 二、什么是迭代器模式

#### 迭代器原理类图分析

Iterator ：迭代器接口由系统提供，含义 hasNext, next, remove

ConcreteIterator :具体的迭代器类，管理迭代

Aggregate :一个统一的聚合接口将客户端和具体聚合解耦

ConcreteAggreage : 具体的聚合持有对象集合， 并提供一个方法，返回一个迭代器， 该迭代器可以正确遍历集合

Client :客户端， 通过 Iterator 和 Aggregate 依赖子类

### 三、使用迭代器模式解决问题

``````//系
class Department {

private String name;//名称
private String desc;//描述
public Department(String name, String desc) {
super();
this.name = name;
this.desc = desc;
}

public String getName() {return name;}

public void setName(String name) {this.name = name;}

public String getDesc() {return desc;}

public void setDesc(String desc) {this.desc = desc;}
}``````

``````class ComputerCollegeIterator implements Iterator {

//这里Department是以数组的方式存放
Department[] departments;

//遍历的位置
int position = 0;

public ComputerCollegeIterator(Department[] departments) {
this.departments = departments;
}

//判断是否还有下一个元素
@Override
public boolean hasNext() {
if (position >= departments.length || departments[position] == null) {
return false;
} else {
return true;
}
}

@Override
public Object next() {
Department department = departments[position];
position += 1;
return department;
}

//删除的方法，默认空实现
@Override
public void remove() {}
}``````

``````class InfoColleageIterator implements Iterator {

//  信息工程学院是以 List 方式存放系
List<Department> departmentList;

//索引
int index = -1;

public InfoColleageIterator(List<Department> departmentList) {
this.departmentList = departmentList;
}

//判断 list 中还有没有下一个元素
@Override
public boolean hasNext() {
if (index >= departmentList.size() - 1) {
return false;
} else {
index += 1;
return true;
}
}

@Override
public Object next() {
return departmentList.get(index);
}

// 空 实 现 remove
@Override
public void remove() {}
}``````

``````interface College {
//学院的名称
public String getName();

//增加系的方法
public void addDepartment(String name, String desc);

//返回一个迭代器,遍历
public Iterator    createIterator();
}``````

``````class ComputerCollege implements College {

//这里Department是以数组的方式存放
Department[] departments;

// 保存当前数组的对象个数
int numOfDepartment = 0;

@Override
public String getName() {
return "计算机学院";
}

@Override
public void addDepartment(String name, String desc) {
//根据传入的信息创建系
Department department = new Department(name, desc);
departments[numOfDepartment] = department;
numOfDepartment += 1;
}

@Override
public Iterator createIterator() {
return new ComputerCollegeIterator(departments);
}
}``````

``````class InfoCollege implements College {

//集合的方式存储
List<Department> departmentList;

@Override
public String getName() {
return "信息工程学院";
}
@Override
public void addDepartment(String name, String desc) {
Department department = new Department(name, desc);
}
@Override
public Iterator createIterator() {
return new InfoColleageIterator(departmentList);
}
}``````

``````class OutPutImpl {

//学院集合
List<College> collegeList;

public OutPutImpl(List<College> collegeList) {
this.collegeList = collegeList;
}

//遍历所有学院,然后调用 printDepartment  输出各个学院的系
public void printCollege() {
//从 collegeList 取出所有学院, Java 中的 List 已经实现Iterator
Iterator<College> iterator = collegeList.iterator();
while (iterator.hasNext()) {
//取出一个学院
College college = iterator.next();
System.out.println("=== " + college.getName() + "=====");
printDepartment(college.createIterator()); //得到对应迭代器
}
}

//输出 学院输出 系
public void printDepartment(Iterator iterator) {
while (iterator.hasNext()) {
Department d = (Department) iterator.next();
System.out.println(d.getName());
}
}
}``````

``````public static void main(String[] args) {

//创建存储迭代类
List<College> collegeList = new ArrayList<College>();

//创建返回对应计算机学院迭代器
ComputerCollege computerCollege = new ComputerCollege();
//创建存储计算机学院的里的系
computerCollege.departments = new Department[5];
//将计算机学院里的系，存储到迭代器里
computerCollege.addDepartment("Java 专业", " Java 专业  ");
computerCollege.addDepartment("PHP 专业", " PHP 专业  ");

//创建返回对应信息学院对应迭代器
InfoCollege infoCollege = new InfoCollege();
//创建存储计算机学院的里的系
infoCollege.departmentList = new ArrayList<Department>();
//将信息学院里的系，存储到迭代器里

//将两个学院的迭代器添加进集合中

//将集合交给帮忙输出类进行输出
OutPutImpl outPutImpl = new OutPutImpl(collegeList);
outPutImpl.printCollege();
}

=== 计算机学院=====
Java 专业
PHP 专业

=== 信息工程学院=====

``````

### 四、迭代器在源码中的使用

``````public static void main(String[] args) {

List<String> list = new ArrayList<>();

Iterator<String> integer = list.iterator();
while(integer.hasNext()){
System.out.println(integer.next());
}
}

Jack``````

``````public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
//....省略关键性的代码
}``````

``````public interface List<E> extends Collection<E> {

int size();

boolean isEmpty();

boolean contains(Object o);

Iterator<E> iterator();

Object[] toArray();

//省略其他关键性代码.....
}``````

``````public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
public Iterator<E> iterator() {
return new Itr();
}
private class Itr implements Iterator<E> {
int cursor;       // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;

Itr() {}

public boolean hasNext() {
return cursor != size;
}

@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}

public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();

try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}

@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}

final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}

//省略其他关键性代码....
}
``````

Itr是ArrayList的一个内部类，本身使用ArrayList里的elementData

Ø 优点

Ø 缺点

### 参考资料

Refactoring.Guru：《深入设计模式》

https://segmentfault.com/a/1190000039135774

Scroll to Top