If you are learning 《Thinking in Java》 This book , We often come into contact with foreach Syntax is mainly used for arrays , We can’t help but wonder , Is it only for this purpose ? It’s not , It can be applied to any Collection object .
We need concrete examples to illustrate the problem :
The following code shows that it can work with foreach Grammar works together is all Collection Properties of objects .
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+"'");
}
}
Running results :
Through the above analysis , We can see that , I’m right . But the underlying implementation ? Or the reason ? Then I will analyze the reasons for you , Why can we work like this , yes Because in Java SE5 Introduced a new one called Iterable The interface of , The interface contains one that can generate Iterator Of Iterator() Method , also Iterable Interface is foreach Used to move in a sequence , That is, if you create any implementation Iterable Class , You can use it for both foreach In the sentence . 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+" ");
}
}
Running results :
The content of this part is temporarily updated here , I hope that’s helpful !
Thank you. ! We grew up together !