迭代器模式属于行为型模式
这种模式用于顺序访问集合对象的元素,不需要知道集合对象的底层表示。
java中ArrayList的实现过程
这个是实现为最简单的实现,对比JDK自己的实现少了很多校验逻辑,仅供学习测试
package com.cans;
import java.util.ArrayList;
import java.util.Iterator;
/**
* 自定义迭代器 倒序输出
*
* @author shenc
* @date 2022-09-06 16:34
**/
public class MyIterator<E> implements Iterator<E>{
int cursor; // index of next element to return
int size;
ArrayList<E> arrayList;
public MyIterator(ArrayList<E> arrayList) {
this.arrayList = arrayList;
this.size = arrayList.size();
this.cursor = arrayList.size();
}
@Override
public boolean hasNext() {
return cursor != 0;
}
@Override
public E next() {
E e = arrayList.get(cursor-1);
cursor --;
return e;
}
}
测试代码
import com.cans.MyIterator;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Iterator;
/**
* 类描述
*
* @author shenc
* @date 2022-09-06 17:02
**/
public class MyIteratorTest {
@Test
public void test1(){
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
Iterator<Integer> iterator = list.iterator();
System.out.println("====================顺序====================");
while (iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println("====================倒序====================");
MyIterator<Integer> myIterator = new MyIterator<>(list);
while (myIterator.hasNext()){
System.out.println(myIterator.next());
}
}
}
结果输出:
顺序
1
2
3
倒序
3
2
1
Process finished with exit code 0