foreach与迭代器

2016-10-26  本文已影响39人  998584f56259

foreach语法主要用于数组,但是它也可以应用于任何Collection对象。如下:

import java.util.*;

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 + "' ");
}
} /* Output:
'Take' 'the' 'long' 'way' 'home'
*///:~

因为cs是一个Collection,所以这段代码展示了能够与foreach一起工作是所有的Collection对象的特性。之所以能够工作是因为在Java SE5中引入了新的被称为Iterable的接口,该接口包含一个能够产生Iterator的iterator()方法,并且Iterable接口被foreach用来在序列中移动,如果我们创建了额任何实现了Iterable的类,都可以用于foreach语法中。

import java.util.*;

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() { // Not implemented
    throw new UnsupportedOperationException();
  }
  
}; 
}   

public static void main(String[] args) {
for(String s : new IterableClass())
  System.out.print(s + " ");
}


} /* Output:
And that is how we know the Earth to be banana-shaped.
*///:~

iterator()方法返回的是实现了Iterator<String>的匿名内部类的实例,该匿名内部类可以遍历数组中的所有单词。

注意,foreach可以用于数组和Collection中,但是并不能用于Map中,还有就是数组可以使用foreach语句,但是并不意味着数组肯定也是一个Iterable。

import java.util.*;

public class ArrayIsNotIterable {

static <T> void test(Iterable<T> ib) {
for(T t : ib)
  System.out.print(t + " ");
}

public static void main(String[] args) {
test(Arrays.asList(1, 2, 3));

String[] strings = { "A", "B", "C" };
// An array works in foreach, but it's not Iterable:
//! test(strings);
// You must explicitly convert it to an Iterable:
test(Arrays.asList(strings));
}
} /* Output:
1 2 3 A B C
*///:~

尝试把数组当做一个Iterable参数传递会导致失败,这说明不存在数组到Iterable的自动转换。

上一篇 下一篇

猜你喜欢

热点阅读