标签:cti next shape ble try entryset util 大量 iterable
foreach语法主要用于数组,但是它也可以用于Collection对象,下面是一个示例
package object; //: holding/ForEachCollections.java // All collections work with foreach. 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是一个Colllection,所以这段代码展示了能够与foreach一起工作是所有Collection对象的特性
之所以能够工作,是因为Iterable接口,该接口包含了一个能够产生Iterator的iterator()方法,并且Iterator接口被foreach用来在序列中移动,因此如果你创建了任何实现了Iterable的类,都可以用于foreach语句中:
package object; //: holding/IterableClass.java // Anything Iterable works with 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() {//返回匿名内部类Iterator<String>的实例,该匿名内部类可以遍历数组中的所以单词 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())(foreach语句调用了Iterator的方法 System.out.print(s + " "); } } /* Output: And that is how we know the Earth to be banana-shaped. *///:~
在java中,大量的类都是Iterable类型,主要包括Collection类(但不包括各种Map),例如下面的代码可以显示所有的操作系统的环境变量:
package object; //: holding/EnvironmentVariables.java import java.util.*; public class EnvironmentVariables { public static void main(String[] args) { for(Map.Entry entry: System.getenv().entrySet()) {//System.getenv()返回一个Map,entrySet()产生一个
//Map.Entry的元素构成的Set,并且这个Set是一个Iterable,因此它可以用于foreach循环 System.out.println(entry.getKey() + ": " + entry.getValue()); } } } /* (Execute to see output) *///:~
foreach可以用于数组和其他任何Iterable,但这不意味着数组肯定也是Iterable,而任何自动包装也不会自动发生,下面示例展示了当尝试将数组当作Iterable参数传递时会导致失败,这说明不存在任何从数组到Iterable的自动转化,必须手工执行这种转换
package object; //: holding/ArrayIsNotIterable.java 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)); //test(strings); } } /* Output: 1 2 3 A B C *///:~
标签:cti next shape ble try entryset util 大量 iterable
原文地址:https://www.cnblogs.com/jiangfeilong/p/10284728.html