Java之Foreach与迭代器

如果你在学习《Thinking in Java》这本书,在前面我们经常会接触到foreach语法主要用于数组,我们不禁会有这样的疑问,它难道仅仅只有这个用途吗?其实不是的,它可以应用于任何的Collection对象。

我们需要具体的实例来说明这个问题:

下面这段代码说明能够与foreach语法一起工作是所有的Collection对象的特性。

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;

public class ForEachCollections {
	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+"'");
	}
}

运行结果:

通过上面的分析,我们可以看出,笔者说的很对。但是底层的实现呢?或者说是原因呢?那么接下来我就来为大家分析分析原因,之所以能够这样工作,是因为在Java SE5引入了新的被称为Iterable的接口,该接口所包含的一个能够产生Iterator的Iterator()方法,并且Iterable接口被foreach用来在序列中移动,也就是说如果你创建了任何实现Iterable的类,都可以将它用于foreach语句中。示例如下:

import java.util.Iterator;

public class IterableClass 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() {
				throw new UnsupportedOperationException();
			}
		};
	}
	public static void main(String[] args) {
		for(String s:new IterableClass())
			System.out.print(s+" ");
	}
}

运行结果:

本部分内容暂时更新到这里,希望对大家有所帮助 !

谢谢大家!我们一起成长!

猜你喜欢

转载自blog.csdn.net/qq_41026809/article/details/90675798