foreach循环的底层实现介绍

增强for循环底层实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.study.iter;

import java.util.ArrayList;
import java.util.List;

public class TestIter {

public static void main(String[] args) {
List<String> list = new ArrayList<String>();

for(String str : list) {
System.out.println(str);
}

}

}

编译后的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.study.iter;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class TestIter {
public TestIter() {
}

public static void main(String[] args) {
List<String> list = new ArrayList();
Iterator var2 = list.iterator();

while(var2.hasNext()) {
String str = (String)var2.next();
System.out.println(str);
}

}
}

从编译后的代码可以看出:
其实现方式为iterator的迭代循环



 评论