到目前为止,foreach语法主要用于数组,但是它也可以应用于任何Collection对象。你实际上已经看到过很多使用ArrayList时用到它的示例,下面是一个更通用的证明:
import java.util.*;
public class ForEachCollections {
/**
* @param args
*/
public static void main(String[] args) {
Collection<String> cs = new LinkedList<String>();
Collections.addAll(cs, "Take the long way home".split(" "));
for(String s : cs) {
System.out.print("'" + s + "' ");
}
}
} /* Output:
'Take' 'the' 'long' 'way' 'home'
*///:~
由于cs是一个Collection,所以这段代码展示了能够与foreach一起工作是所有Collection对象的特性。
之所以能够工作,是因为Java SE5引入了新的被称为Iterable的接口,该接口包含一个能够产生Iterator的iterator方法,并且Iterable接口被foreach用来在序列中移动。因此如果你创建了任何实现Iterable的类,都可以将它用于foreach语句中:
package com.mldn.collection;
import java.util.Iterator;
public class IterableClass implements Iterable<String>{
private String[] words = ("And that is how we know the Earth to be banana-shaped.").split(" ");
public static void main(String[] args) {
/* for(String s : new IterableClass()) {
System.out.print(s + " ");
} */
IterableClass ic = new IterableClass();
Iterator<String> it = ic.iterator();
while(it.hasNext()) {
System.out.print(it.next() + " ");
}
}
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() { // Not implemented
throw new UnsupportedOperationException();
}
};
}
}
Foreach与迭代器
最新推荐文章于 2023-07-19 19:01:47 发布