/** * 迭代器模式:java集合中有通过迭代器来遍历的方式,通过迭代器遍历,隐藏了容器内部的组成,而普通的forEach遍历,是可以知道组成是啥的;此处模拟迭代器的实现; * 迭代器最重要的2个方法:hasNext(),next(),通过自定义一个集合,集合内部集成迭代器来遍历自定义集合 * * */ //迭代器接口 public interface MyIterator { boolean hasNext(); Object next(); } //集合接口 public interface MyList { MyIterator getIterator(); } //结合实现类,内部类实现了迭代器 public class ArrList implements MyList { private Integer defualtCapacity=10; private Object[] arr=null; private int size=0; public ArrList() { arr=new Object[defualtCapacity]; } public ArrList(Integer capacity) { if(null!=capacity && capacity>0){ defualtCapacity=capacity; } arr=new Object[defualtCapacity]; } //集合新增内容 public boolean add(Object obj){ if(arr.length>size){ arr[size]=obj; size++; return true; }else { //todo 扩容 } return false; } //获取集合容量 public int size(){ return size; } @Override public MyIterator getIterator() { return new MyIteratorImpl(); } //迭代器实现类 private class MyIteratorImpl implements MyIterator{ private int index=0; @Override public boolean hasNext() { if(index<size){ return true; } return false; } @Override public Object next() { Object o = arr[index]; index++; return o; } } } public class Test { public static void main(String[] args) { //创建容量为20的集合 ArrList arrList = new ArrList(20); arrList.add("haha"); arrList.add("kk"); arrList.add("a"); arrList.add("b"); arrList.add("c"); arrList.add("d"); System.out.println(arrList.size());//集合的长度 //遍历集合 MyIterator iterator = arrList.getIterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); } } }