//建立两个arraylist对象
Collection al = new ArrayList(); //al1添加元素
al.add("name1"); al.add("name4"); al.add("name3"); Iterator it=al.iterator(); while(it.hasNext()) { System.out.println(it.next()); }
for(Iterator it=al.iterator();it.hasNext();) { System.out.println(it.next()); }
for()的好处:更节约内存java
Iterator定义在了循环内部,在循环结束后,it就被释放了,数据结构
而在While中it定义在了循环外面,循环结束后对象依然存在,可是却没什么用处,就形成了内存的浪费this
其实就是集合的取出方式。spa
【通俗的讲:取一个在就判断一下集合中还有没有元素,有就取出,没有就结束】code
next();对象
hasNext();blog
remove();内存
Iterator it=al.iterator(); while(it.hasNext()) { System.out.println(it.next()); }
迭代器用于取出集合中的元素,各类集合的底层数据结构并不相同,因此存取方式是不一样的,每一个集合都具有取出的操做,可是集合的取出比较复杂,不止一个动做,就将取出这个动做封装成了一个对象rem
定义在内部的缘由:get
迭代器操做的是集合内部的元素,定义在类的内部更加方便
若是建立在外部,还须要建立集合对象
Iterator方法的最初定义是在AbstractList这个类中,他的方法实现很简单就是return了一个Itr对象,
Itr是什么呢?
在上图中能够看到,它是定义在AbstractList这个类里面的内部类
在他的内部定义了咱们常常使用的hasNext(),Next(),remove()
而后在Iterator()里面返回了Itr对象
private class Itr implements Iterator<E> { int cursor = 0; int lastRet = -1; int expectedModCount = modCount; public boolean hasNext() { return cursor != size(); } public E next() { checkForComodification(); try { E next = get(cursor); lastRet = cursor++; return next; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } } public void remove() { if (lastRet == -1) throw new IllegalStateException(); checkForComodification(); try { AbstractList.this.remove(lastRet); if (lastRet < cursor) cursor--; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException e) { throw new ConcurrentModificationException(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }