Java and the Foreach iterators

If you're learning "Thinking in Java" book, in front of our often come into contact foreach syntax is mainly used in the array, we can not help but have some questions, just do it only for this purpose it? Well, not exactly, it can be applied to any Collection object.

We need specific examples to illustrate the problem:

 

The following code illustrates able to work with foreach syntax is characteristic of all the Collection object.

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+"'");
	}
}

operation result:

Through the above analysis, we can see that, I said it right. But the underlying achieve it? Or is the problem then? So then I come to you the reason analysis, has been able to work this way, is because in Java SE5 introduced a new interface is called Iterable, the interface contains a can produce Iterator Iterator's () method, and foreach Iterable interface is used to move in the sequence, which means that if you create any class that implements Iterable, can use it for foreach statement. Examples are as follows:

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+" ");
	}
}

operation result:

 

This section is being updated to be here, we want to help!

thank you all! We grow together!

 

Guess you like

Origin blog.csdn.net/qq_41026809/article/details/90675798