为什么这种普通数组(int[])为什么用foreach循环遍历 感觉不是只有那些llist set 集合才可以这样写吗(因为实现了iterator接口) 而普通数组?
for(int b : a){
System.out.Println(b);
}
你可以看看这个的实现源代码,实际上他的实现也是按照for(int i=0;i<9;i++){//代码}这么实现的。
foreach它内部就是实现了for循环。
你这个算不上迭代器,就是循环
int数组的数据结构和list是一样的。。list就是用数组实现的。 /**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return true (as specified by {@link Collection#add})
*/
public boolean add(E e) {
ensureCapacity(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
这应该和foreach的内部实现有关。
foreach遍历更加简洁
你可以理解成超级for循环
因为数组也实现了迭代器接口。
本质上一个对象能不能迭代,并不取决于它的内部实现,而是取决于它是否实现了迭代器(hasNext和next两个方法)。
参考:http://blog.csdn.net/wanghuan203/article/details/7279742
一般情况,两种方式都可以的。只是for循环的话,怎么遍历都行的;如果foreach的话 只能进行正序遍历的……