增强了for array的循环 [英] Enhanced for loop with array
问题描述
我看到如下所示的一行代码:
I saw one line of code like below:
for (String w : words) sentence.add(w); // words is declared as String[] words = ...;
据我所知,我认为能够以这种格式编写循环,我们需要'words'是实现Iterable接口并覆盖iterator()函数的类的实例。
但'words'是String数组的类型,这对于循环格式怎么能正确?
To my knowledge, I think that to be able to write for loop in this format, we need the 'words' being an instance of a class which implements Iterable interface and override the iterator() function. But 'words' is of type String array, how can this for loop format correct?
有人可以给我一些提示吗?
Can someone give me some tips please?
推荐答案
for-each构造也适用到数组,它隐藏
索引变量而不是迭代器。以下方法
返回int数组中值的总和:
The for-each construct is also applicable to arrays, where it hides the index variable rather than the iterator. The following method returns the sum of the values in an int array:
// Returns the sum of the elements of a
int sum(int[] a) {
int result = 0;
for (int i : a)
result += i;
return result;
}
来自 JLS的§14.14.2( Java语言规范):
And from §14.14.2 of the JLS (the Java Language Specification):
增强的for语句具有以下形式:
The enhanced for statement has the form:
EnhancedForStatement:
for ( FormalParameter : Expression ) Statement
Expression
的类型必须是 Iterable
或数组类型,或
编译时发生错误。
The type of the Expression
must be Iterable
or an array type, or a
compile-time error occurs.
但请注意,数组未实现 Iterable
;来自 JLS的§10.1:
But note that arrays don't implement Iterable
; from §10.1 of the JLS:
数组类型的直接超类是
Object
。
每个数组类型都实现接口 Cloneable
和 java.io.Serializable
。
Every array type implements the interfaces Cloneable
and java.io.Serializable
.
这篇关于增强了for array的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!