@(Java知識點總結)[Java, Java容器]java
Iterator對象稱做迭代器,用於方便地實現對容器內元素的遍歷操做
Iterator接口定義以下:this
HashSet set = new HashSet(); set.add("1" ); set.add("2" ); set.add("3" ); /*Iterator it = set.iterator(); while (it.hasNext()) { String obj = (String) it.next(); System.out.println(obj); }*/ for (Iterator it = set.iterator(); it.hasNext();) { String obj = (String) it.next(); System.out.println(obj); }
/** * Iterator實現原理 */ private class Itr implements Iterator<E> { int cursor = 0; //遊標 int lastRet = -1; //上一次遍歷元素的下標 public boolean hasNext() { return cursor != size(); } public E next() { checkForComodification(); try { int i = cursor; E next = get(i); lastRet = i; cursor = i + 1; return next; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { AbstractList.this.remove(lastRet); if (lastRet < cursor) cursor--; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException e) { throw new ConcurrentModificationException(); } } }