// publicvoidprintCollege(){ Iterator<College> iterator = collegeList.iterator(); while (iterator.hasNext()){ //取出一个学院 College college = iterator.next(); System.out.println("========="+ college.getName() +"========"); printDepartment(college.createIterator()); } }
//输出 publicvoidprintDepartment(Iterator iterator){ while (iterator.hasNext()){ Department d = (Department) iterator.next(); System.out.println(d.getName()); } } }
客户端
1 2 3 4 5 6 7 8 9
publicclassClient{ publicstaticvoidmain(String[] args){ List<College> collegeList = new ArrayList<>(); collegeList.add(new ComputeCollege()); collegeList.add(new InfoCollege()); OutPutImpl outPut = new OutPutImpl(collegeList); outPut.printCollege(); } }
publicclassArrayList<E> extendsAbstractList<E> implementsList<E>, RandomAccess, Cloneable, java.io.Serializable { transient Object[] elementData; public Iterator<E> iterator(){ returnnew Itr(); } //内部类 privateclassItrimplementsIterator<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() {}
publicbooleanhasNext(){ return cursor != size; }
@SuppressWarnings("unchecked") public E next(){ checkForComodification(); int i = cursor; if (i >= size) thrownew NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) thrownew ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; }
publicvoidremove(){ if (lastRet < 0) thrownew IllegalStateException(); checkForComodification();