遍历ArrayList,Iterator和for循环哪个更快?

zxcvvcxz127 zxcvvcxz127 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
大家都说Iterator更快,但我测了一下,发现for循环更快,测试代码如下:

public static void main(String[] args) {
long start,end,forStart,forEnd;
ArrayList<Integer> al=new ArrayList<Integer>();
for(int i=0;i<900000;i++){
al.add(new Integer(4));
}

forStart=System.currentTimeMillis();
for(int j=0;j<al.size();j++){
al.get(j);
}
forEnd=System.currentTimeMillis();

Iterator<Integer> it=al.iterator();
start=System.currentTimeMillis();
while(it.hasNext()){
it.next();
}
end=System.currentTimeMillis();

System.out.println("for用时:"+(forEnd-forStart)+"\nIterator用时:"+(end-start));
}



运行结果:

for用时:16
Iterator用时:31

请高手解释一下……
...全文

相关推荐

评论 64
收藏 已收藏
分享
返回顶部
zxcvvcxz127
Java 51,407 成员 86,126 内容