反向迭代器的实现
class ReversibleArrayList<T> extends ArrayList<T> {
public ReversibleArrayList(Collection<T> t) {
super(t);
}
public Iterable<T> reversed(){
return new Iterable<T>() {
public Iterator<T> iterator() {
return new Iterator<T>() {
int current = size() - 1;
@Override
public boolean hasNext() {
return current > -1;
}
@Override
public T next() {
return get(current--);
}
};
}
};
}
}
public class AdapterMethodIdiom {
public static void main(String[] args) {
ReversibleArrayList<String> al = new ReversibleArrayList<>(Arrays.asList("who am i , i don't know".split(" ")));
for(String s : al.reversed()){
System.out.print("'" + s + "'");
}
}
}
类继承自带有Iterator(),都能通过重写实现不一样的迭代功能。
|