Foreach与迭代器


到目前为止,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();
}
};
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值