迭代Iterator的用法
迭代→遍歷:
- 一個標(biāo)準化遍歷各類容器里面的所有對象的方法類(典型的設(shè)計模式)
- 把訪問邏輯從不同類型的集合類中抽象出來,從而避免向客戶端暴露集合的內(nèi)部結(jié)構(gòu)?
迭代(Iterator)與枚舉(Enumeration)的區(qū)別:
一、未使用Iterator
- ?數(shù)組遍歷:
? ? 上述實例缺點:
二、使用Iterator
- Iterator模式用同一種邏輯來遍歷集合,使得客戶端自身不需要來維護集合的內(nèi)部結(jié)構(gòu),所有的內(nèi)部狀態(tài)都由Iterator來維護。
- 客戶端從不直接和集合類打交道,它總是控制Iterator,向它發(fā)送"向前","向后","取當(dāng)前元素"的命令,就可以間接遍歷整個集合。
1.使一個類可迭代的步驟:
Step1:在類聲明中加入implements Iterable<Item>,對應(yīng)的接口為(即java.lang.Iterator)
public interface Iterable<Item>{Iterator<Item> iterator(); }
Step2:在類中實現(xiàn)iterator()方法,返回一個自己定義的迭代器Iterator<Item>
public Iterator<Item> iterator(){//如果需要逆序遍歷數(shù)組,自定義一個逆序迭代數(shù)組的迭代器return new ReverseArrayIterator(); }Step3:在類中設(shè)置內(nèi)部類(如private class?ReverseArrayIterator()?),內(nèi)部類聲明中加入implements Iterator<Item>,對應(yīng)的接口為(即java.util.Iterator)
public interface Iterator { boolean hasNext(); Object next(); void remove(); }?
2.使用Iterator實例(摘自算法(第四版)):
下壓(LIFO)棧--能動態(tài)調(diào)整數(shù)組大小(學(xué)習(xí)迭代器只需要重點看后面兩大段):
import java.util.Iterator; import java.util.NoSuchElementException;public class ResizingArrayStack<Item> implements Iterable<Item> {private Item[] a; // array of itemsprivate int n; // number of elements on stack/*** Initializes an empty stack.*/public ResizingArrayStack() {a = (Item[]) new Object[2];n = 0;}/*** Is this stack empty?* @return true if this stack is empty; false otherwise*/public boolean isEmpty() {return n == 0;}/*** Returns the number of items in the stack.* @return the number of items in the stack*/public int size() {return n;}// resize the underlying array holding the elementsprivate void resize(int capacity) {assert capacity >= n;// textbook implementationItem[] temp = (Item[]) new Object[capacity];for (int i = 0; i < n; i++) {temp[i] = a[i];}a = temp;// alternative implementation// a = java.util.Arrays.copyOf(a, capacity); }/*** Adds the item to this stack.* @param item the item to add*/public void push(Item item) {if (n == a.length) resize(2*a.length); // double size of array if necessarya[n++] = item; // add item }/*** Removes and returns the item most recently added to this stack.* @return the item most recently added* @throws java.util.NoSuchElementException if this stack is empty*/public Item pop() {if (isEmpty()) throw new NoSuchElementException("Stack underflow");Item item = a[n-1];a[n-1] = null; // to avoid loiteringn--;// shrink size of array if necessaryif (n > 0 && n == a.length/4) resize(a.length/2);return item;}/*** Returns (but does not remove) the item most recently added to this stack.* @return the item most recently added to this stack* @throws java.util.NoSuchElementException if this stack is empty*/public Item peek() {if (isEmpty()) throw new NoSuchElementException("Stack underflow");return a[n-1];}/*** Returns an iterator to this stack that iterates through the items in LIFO order.* @return an iterator to this stack that iterates through the items in LIFO order.*/public Iterator<Item> iterator() {return new ReverseArrayIterator();}// an iterator, doesn't implement remove() since it's optionalprivate class ReverseArrayIterator implements Iterator<Item> {private int i;public ReverseArrayIterator() {i = n-1;}public boolean hasNext() {return i >= 0;}public void remove() {throw new UnsupportedOperationException();}public Item next() {if (!hasNext()) throw new NoSuchElementException();return a[i--];}} }遍歷時用foreach語句:
ResizingArrayStack<String> stack = new ResizingArrayStack<String>();for (String str:stack ) {System.out.println(str);}?
?
作者: 鄒珍珍(Pearl_zhen)
出處: http://www.cnblogs.com/zouzz/
聲明:本文版權(quán)歸作者和博客園共有,歡迎轉(zhuǎn)載,但未經(jīng)作者同意必須保留此段聲明,且在文章頁面明顯位置給出 原文鏈接 如有問題, 可郵件(zouzhenzhen@seu.edu.cn)咨詢.
轉(zhuǎn)載于:https://www.cnblogs.com/zouzz/p/6090105.html
總結(jié)
以上是生活随笔為你收集整理的迭代Iterator的用法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 6-2-2:STL之string——st
- 下一篇: ZooKeeper系列(四)