在平时Java程序中,应用比较多的就是对Collection集合类的foreach遍历,foreach之所以能工作,是因为这些集合类都实现了Iterablei接口,该接口中定义了Iterator迭代器的
产生方法,并且foreach就是通过Iterable接口在序列中进行移动。
Iterablei接口API:
package java.lang; import java.util.Iterator; public interface Iterable { public abstract Iterator iterator(); }
该接口中定义了产生Iterator迭代器的方法;
package java.util; public interface Iterator { public abstract boolean hasNext(); public abstract Object next(); public abstract void remove(); }
因此如果自己建的一个类也实现了Iterable接口,并且实现了具体产生Iterator的方法,foreach方法也是同样适用于新建类的,结合适配器模式的一个样例如下:
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Random; public class IteartorClass implements Iterable<String> { protected static final String[] WORDS = "just for test iterable interface".split(" "); @Override public Iterator<String> iterator() { return new Iterator<String>() { private int index = 0; public boolean hasNext() { return index < WORDS.length - 1; } @Override public String next() { return WORDS[index++]; } @Override public void remove() { } }; } public static void main(String[] args) { mutileIteratorClass class1 = new mutileIteratorClass(); for (String string : class1.randomNized()) { System.out.print(string + " "); } System.out.print(" "); for (String string : class1.reversed()) { System.out.print(string + " "); } } } class mutileIteratorClass extends IteartorClass { public Iterable<String> reversed() { return new Iterable<String>() { public Iterator<String> iterator() { return new Iterator<String>() { private int index = WORDS.length - 1; public boolean hasNext() { return index >= 0; } public String next() { return WORDS[index--]; } public void remove() { } }; } }; } public Iterable<String> randomNized() { return new Iterable<String>() { public Iterator<String> iterator() { List<String> list = new ArrayList<String>(Arrays.asList(WORDS)); Collections.shuffle(list, new Random(20)); return list.iterator(); } }; } }