forEach与迭代器

任何实现了Iterable接口的类,都可以用forEach语句,并且Java中大部分的Collection都可以用forEach,除了Map
1
import java.util.*; 2 public class AdapterMethodiom implements Iterable<String> 3 { 4 protected String[] words = ("hello world this is a good day").split(" "); 5 public Iterator<String> iterator() { 6 return new Iterator<String>(){ 7 private int index =0; 8 9 @Override 10 public boolean hasNext() { 11 return index < words.length; 12 } 13 14 @Override 15 public String next() { 16 17 return words[index++]; 18 } 19 20 }; 21 22 } 23 public static void main(String[] args) { 24 for(String s:new AdapterMethodiom()) 25 { 26 System.out.println(s+" "); 27 } 28 29 } 30 }
原文地址:https://www.cnblogs.com/vector11248/p/7742544.html