遍历列表的三种方法

JDK1.5之后,遍历列表操作至少有三种方法:ForEach操作,迭代器和for循环。

使用方法如下:

String[] strs = new String[]{"1", "2", "3"};
List<String> list = Arrays.asList(strs);
for (String s: list) {//ForEach操作
    System.out.println(s);
}

for (Iterator it = list.iterator(); it.hasNext();) {//迭代器
    System.out.println(it.next());
}

for (int i=0; i<list.size(); i++) {//for循环
    System.out.println(list.get(i));
}

这三种遍历操作效率对比如下:

对于ArrayList:

for循环 > 迭代器 > ForEach操作

对于LinkedList:

迭代器 > ForEach操作,不要使用for循环!

ForEach操作效率小于迭代器的原因是,ForEach循环会被解析成下面的代码:

for (Iterator it = list.iterator(); it.hasNext();) {
    String s = (String) it.next();
    String s1 = s;//多余的赋值
}

而迭代器遍历被解析为:

String s2;
for (Iterator it = list.iterator(); it.hasNext();) {
    s2 = (String) it.next();
}

ForEach循环中存在一步多余的赋值操作。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值