考虑:
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循环会是什么样子?
当前回答
使用较旧的Java版本(包括Java7),可以使用foreach循环,如下所示。
List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");
for(String item : items) {
System.out.println(item);
}
以下是Java8中使用for-each循环的最新方法(使用forEach+lambda表达式或方法引用循环List)。
Lambda公司
// Output: A,B,C,D,E
items.forEach(item->System.out.println(item));
方法参考
// Output: A,B,C,D,E
items.forEach(System.out::println);
有关详细信息,请参阅“Java 8 For Each examples”。
其他回答
for (Iterator<String> i = someIterable.iterator(); i.hasNext();) {
String item = i.next();
System.out.println(item);
}
注意,如果需要使用i.remove();在循环中,或者以某种方式访问实际的迭代器,不能使用for(:)习惯用法,因为实际的迭代器只是推断出来的。
正如Denis Bueno所指出的,这段代码适用于实现Iterable接口的任何对象。
此外,如果for(:)习惯用法的右侧是数组而不是Iterable对象,则内部代码使用int索引计数器并检查array.length。请参阅Java语言规范。
foreach循环语法为:
for (type obj:array) {...}
例子:
String[] s = {"Java", "Coffe", "Is", "Cool"};
for (String str:s /*s is the array*/) {
System.out.println(str);
}
输出:
Java
Coffe
Is
Cool
警告:可以使用foreach循环访问数组元素,但不能初始化它们。为此使用原始for循环。
警告:必须将数组的类型与其他对象匹配。
for (double b:s) // Invalid-double is not String
如果要编辑元素,请使用原始for循环,如下所示:
for (int i = 0; i < s.length-1 /*-1 because of the 0 index */; i++) {
if (i==1) //1 because once again I say the 0 index
s[i]="2 is cool";
else
s[i] = "hello";
}
现在,如果我们将数据转储到控制台,我们会得到:
hello
2 is cool
hello
hello
这看起来很疯狂,但嘿,它奏效了
List<String> someList = new ArrayList<>(); //has content
someList.forEach(System.out::println);
这是可行的。魔术
使用forEach:
int[] numbers = {1,2,3,4,5};
Arrays.stream(numbers).forEach(System.out::println);
答复:
1
2
3
4
5
The process finished with exit code 0
PS:您需要一个Array(int[]数字),然后导入java.util.Arrays;
每个的构造也对数组有效。例如
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--它没有成为列表,或来自甚至你自己的类型,因此,可以与此一起使用语法。