@(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(); } } }