同的实现,基于此来提供多个不 同功能的迭代器。Links5.java中提供了两种不同功能的迭代器, 除了常规的顺序遍历迭代器外,还提供一个遍历偶序号元素的迭代 器。
Links5.java
package com.zj.iterator.standard;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Links5<T> implements Iterable<T> {
private List<T> items = new ArrayList<T>();
public void add(T x) {
items.add(x);
}
public Iterator<T> iterator() {
return new Iterator<T>() {
private int index = 0;
public boolean hasNext() {
return index < items.size();
}
public T next() {
return items.get(index++);
}
public void remove() { // Not implemented
throw new UnsupportedOperationException ();
}
};
}
public Iterable<T> even() {
return new Iterable<T>() {
public Iterator<T> iterator() {
return new Iterator<T>() {
private int index = 0;
public boolean hasNext() {
return index < items.size();
}
public T next() {
index += 2;
return items.get(index - 2);
}
public void remove() { // Not implemented
throw new UnsupportedOperationException();
}
};
}
};
}
public static void main(String[] args) {
Links5<Integer> links = new Links5<Integer>();
for (int i = 1; i < 6; i++)
links.add(i);
// use Foreach default
for (Integer integer : links)
System.out.print(integer + " ");
System.out.println();
// use Foreach even
for (Integer integer : links.even())
System.out.print(integer + " ");
}
}
本文出自 “子 孑” 博客,请务必保留此出处
http://zhangjunhd.blog.51cto.com/113473/69969 |