前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java中普通for循环和增强for循环的一些区别

Java中普通for循环和增强for循环的一些区别

作者头像
XING辋
发布2019-03-26 11:34:42
1.5K0
发布2019-03-26 11:34:42
举报
文章被收录于专栏:M莫的博客M莫的博客

Java中for的几种常见形式

  1. For loop using index. for (int i = 0; i < arr.length; i++) { type var = arr[i]; body-of-loop }
  2. Loop using explicit iterator. for (Iterator<type> iter = coll.iterator(); iter.hasNext(); ) { type var = iter.next(); body-of-loop }
  3. Foreach loop over all elements in arr. for (type var : coll) { body-of-loop }

For循环用来处理哪些数据结构

  1. 数组
代码语言:javascript
复制
int[] a = {1,2,3,4,5,6};
int[] b = new int[]{1,2,3,4,5,6};
int[] c = new int[6];

for (int i = 0; i < a.length; i++) {
    System.out.println(i);
}
for (int i : a) {
    System.out.println(i);
}
  1. 实现了java.util.Iterator的类
代码语言:javascript
复制
import java.util.Iterator;

/**
 * Created by MoXingwang on 2017/6/30.
 */
public class IterableTest<E> implements Iterable<E> {

    public static void main(String[] args) {
        IterableTest<Integer> integers = new IterableTest<Integer>();
        for (Integer integer : integers) {
            System.out.println(integer);
        }
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator() {

            @Override
            public boolean hasNext() {
                //...
                return false;
            }

            @Override
            public Object next() {
                //...
                return null;
            }

            @Override
            public void remove() {
                //...
            }
        };
    }
}

普通for遍历和增强for的一些区别

增强的for循环的底层使用迭代器来实现,所以它就与普通for循环有一些差异

  1. 增强for使用增强for循环的时候不能使用集合删除集合中的元素;
  2. 增强for循环不能使用迭代器中的方法,例如remove()方法删除元素;
  3. 与普通for循环的区别:增强For循环有遍历对象,普通for循环没有遍历对象;

对于实现了RandomAccess接口的集合类,推荐使用普通for,这种方式faster than Iterator.next

The RandomAccess interface identifies that a particular java.util.List implementation has fast random access. (A more accurate name for the interface would have been “FastRandomAccess.”) This interface tries to define an imprecise concept: what exactly is fast? The documentation provides a simple guide: if repeated access using the List.get( ) method is faster than repeated access using the Iterator.next( ) method, then the List has fast random access. The two types of access are shown in the following code examples.

参考资料

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-08-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Java中for的几种常见形式
  • For循环用来处理哪些数据结构
  • 普通for遍历和增强for的一些区别
  • 参考资料
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档