foreach原理是不是这样的: Collection x = new ArrayList(); x.add(1);x.add(2);Iterator y = x.iterrator(); while(x.hasNext){ ...... }
原理是这样的:一、对于实现了 Iterable 接口中类,编译器内部转换成类似这样的格式: for(Iterator<T> i = list.iterator(); i.hasNext(); ) { T t = i.next(); } 二、对于数组,编译器内部转换成类似这样的格式: for(int i = 0; i < nums.length; i++) { int n = nums[i]; }
foreach在遍历集合类时又没有for循环快,何必一定要用foreach?
String[] strs = {"1","2"}; int i =0; foreach(String str : strs){ System.out.println(str); i++; }
foreach()
{
//i i++;
}
Collection x = new ArrayList();
x.add(1);x.add(2);Iterator y = x.iterrator();
while(x.hasNext){
......
}
for(Iterator<T> i = list.iterator(); i.hasNext(); ) {
T t = i.next();
}
二、对于数组,编译器内部转换成类似这样的格式:
for(int i = 0; i < nums.length; i++) {
int n = nums[i];
}
int i =0;
foreach(String str : strs){
System.out.println(str);
i++;
}
您的意思是用for(int i : ints) 假设后面的是数组 在里面可以用i?...