考虑:
List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
for (String item : someList) {
System.out.println(item);
}
如果不使用for each语法,等价的for循环会是什么样子?
考虑:
List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
for (String item : someList) {
System.out.println(item);
}
如果不使用for each语法,等价的for循环会是什么样子?
当前回答
每个的构造也对数组有效。例如
String[] fruits = new String[] { "Orange", "Apple", "Pear", "Strawberry" };
for (String fruit : fruits) {
// fruit is an element of the `fruits` array.
}
这基本上等同于
for (int i = 0; i < fruits.length; i++) {
String fruit = fruits[i];
// fruit is an element of the `fruits` array.
}
因此,总体总结如下:[nsayer]以下是正在发生的事情的较长形式:
for(Iterator<String>i=someList.iiterator();i.hasNext();){字符串项=i.next();System.out.println(项);}注意,如果您需要使用i.移除();或访问实际的迭代器不能使用for(:)习惯用法,因为实际的迭代器只是推断。
[丹尼斯·布埃诺]
nsayer的回答暗示了这一点,但是值得注意的是,OP用于(..)当“someList”为任何实现的东西java.lang.Iterable--它没有成为列表,或来自甚至你自己的类型,因此,可以与此一起使用语法。
其他回答
Java“for each”循环构造将允许对两种类型的对象进行迭代:
T[](任何类型的数组)java.lang.Iterable<T>
Iterable<T>接口只有一个方法:Iterator<T>迭代器()。这对Collection<T>类型的对象有效,因为Collection<T<接口扩展了Iterable<T>。
它看起来像这样。非常粗糙。
for (Iterator<String> i = someList.iterator(); i.hasNext(); )
System.out.println(i.next());
Sun文档中对每一项都有很好的描述。
在Java8中,他们引入了forEach。使用它列表,可以循环地图。
使用for each循环列表
List<String> someList = new ArrayList<String>();
someList.add("A");
someList.add("B");
someList.add("C");
someList.forEach(listItem -> System.out.println(listItem))
or
someList.forEach(listItem-> {
System.out.println(listItem);
});
使用for each循环映射
Map<String, String> mapList = new HashMap<>();
mapList.put("Key1", "Value1");
mapList.put("Key2", "Value2");
mapList.put("Key3", "Value3");
mapList.forEach((key,value)->System.out.println("Key: " + key + " Value : " + value));
or
mapList.forEach((key,value)->{
System.out.println("Key : " + key + " Value : " + value);
});
维基百科中提到的foreach循环的概念如下:
然而,与其他for循环构造不同,foreach循环通常保持没有明确的反击:他们基本上说“这样做而不是“做x次”。这样可以避免潜在的一个错误,使代码更容易阅读。
因此,foreach循环的概念描述了该循环不使用任何显式计数器,这意味着不需要使用索引在列表中遍历,因此它将用户从一个错误中解脱出来。为了描述这一错误的一般概念,让我们举一个使用索引在列表中遍历的循环的例子。
// In this loop it is assumed that the list starts with index 0
for(int i=0; i<list.length; i++){
}
但是假设列表以索引1开始,那么这个循环将抛出一个异常,因为它将在索引0处找不到元素,这个错误被称为off-by-one错误。因此,为了避免这一错误,使用了foreach循环的概念。可能还有其他优点,但这就是我认为使用foreach循环的主要概念和优点。
在Java 8功能中,您可以使用以下功能:
List<String> messages = Arrays.asList("First", "Second", "Third");
void forTest(){
messages.forEach(System.out::println);
}
输出
First
Second
Third