Iterable接口

来源:互联网 发布:淘宝号申请注册 编辑:程序博客网 时间:2024/06/08 12:10

Iterable接口包含一个产生Iterator的iterator的方法,用于foreach中移动

下面是一个例子:

import java.util.*;public class IteratableClass implements Iterable<String>{protected String [] words="and that is how we know the earth to be banana-shaped".split(" ");public Iterator<String> iterator(){return new Iterator<String>(){private int index=0;public boolean hasNext(){return index<words.length;}public String next(){return words[index++];}public void remove(){}};}/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubfor(String s:new IteratableClass()){System.out.println(s+" ");}}}

下面用适配器方法产生反向的迭代的方法:

import java.util.*;public class ReversibleArrayList<T> extends ArrayList<T>{public ReversibleArrayList(Collection<T> c){super(c);}public Iterable<T> reversed(){return new Iterable<T>(){public Iterator<T> iterator(){return new Iterator<T>(){int current=size()-1;public boolean hasNext(){return current>0;}public T next(){return get(current--);}public void remove(){}};}};}}

import java.util.*;public class AdapterMethodIdiom {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubReversibleArrayList<String> ral=new ReversibleArrayList<String>(Arrays.asList("to be or not to be".split(" ")));for(String s:ral)System.out.print(s+" ");System.out.println();for(String s:ral.reversed())System.out.print(s+" ");}}




0 0