歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java 經典實例:自定義迭代器

Java 經典實例:自定義迭代器

日期:2017/3/1 9:08:47   编辑:Linux編程

編寫自己的Iterator,實現Iterator接口,這裡多說一句,實現Iterable後,可以用“foreach”循環遍歷你的對象。

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
* 演示Iterator和Iterable接口,並說明怎樣編寫一個用於對象數組的簡單迭代器。
*/
public class AarrayIterator<T> implements Iterable<T>, Iterator<T> {
private final static String[] names = {"rose", "petunia", "tulip"};

public static void main(String[] args) {
AarrayIterator<String> arrayIterator = new AarrayIterator<>(names);

// Java 5,6的方式
for (String s : arrayIterator) {
System.out.println(s);
}

// Java 8的形式
arrayIterator.forEach(System.out::println);
}

/**
* 要遍歷的數據
**/
protected T[] data;

protected int index = 0;

/**
* 構造一個AarryIterator對象。
*
* @param data 被迭代的對象數組
*/
public AarrayIterator(final T[] data) {
setData(data);
}

/**
* 設置(重置)數組為給定的數組,重置迭代器。
* 參數d代表被迭代的數組對象。
*
* @param d 被迭代的數組對象
*/

public void setData(final T[] d) {
this.data = d;
index = 0;
}

/**
* 如果不是末尾,返回true,例如,if next()語句將成功執行。
* 否則返回false,執行if next()語句會拋出異常。
*
* @return
*/
public boolean hasNext() {
return index < data.length;
}

/**
* 返回該數據的下一個元素
*
* @return
*/
public T next() {
if (hasNext()) {
return data[index++];
}
throw new NoSuchElementException("only " + data.length + " elements");
}

public void remove() {
throw new UnsupportedOperationException("This demo Iterator does not implement the remove method");
}

/**
* Iterator的方法
*
* @return
*/
public Iterator<T> iterator() {
index = 0;
return this;
}
}

執行結果:

rose
petunia
tulip
rose
petunia
tulip

Copyright © Linux教程網 All Rights Reserved