Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 016ec72

Browse filesBrowse files
committed
Merge pull request giantray#46 from ArronDon/master
Create how-does-the-java-for-each-loop-work.md
2 parents f092ace + 5d872de commit 016ec72
Copy full SHA for 016ec72

File tree

Expand file treeCollapse file tree

1 file changed

+23
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+23
-0
lines changed
+23Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
## Java的foreach循环是如何工作的?
2+
### 问题
3+
````java
4+
List<String> someList = new ArrayList<String>();
5+
// add "monkey", "donkey", "skeleton key" to someList
6+
for (String item : someList) {
7+
System.out.println(item);
8+
}
9+
````
10+
如果不用for each语法,等价的循环语句是什么样的?
11+
### 回答
12+
````java
13+
for(Iterator<String> i = someList.iterator(); i.hasNext(); ) {
14+
String item = i.next();
15+
System.out.println(item);
16+
}
17+
````
18+
记住,如果需要在循环中使用i.remove;或者以某种方式获取实际的iterator,你不能使用for(:)语法,因为实际的Iterator很难被推断出来。
19+
正如Denis Bueno写的那样,这种代码对任何实现了Iterable接口的对象都奏效。
20+
此外,如果for(:)句法中右侧是一个数组而不是一个可迭代对象,那么内部代码用一个int型的计数器来防止数组越界。详见Java Language Specification:
21+
http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14.2
22+
23+
stackoverflow链接:http://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.