首页 > 编程知识 正文

遍历列表的两种方法,list嵌套list 遍历

时间:2023-05-05 11:55:39 阅读:46217 作者:2368

提问场景在IDEA中以传统的for循环遍历列表时,会呈现“‘forloopreplaceablewithforeach…”。 为什么要出示? foreach的效率高吗? 着手实验。

与思考相比,首先,foreach其实是语法糖,它简化了迭代程序,可以遍历数组和集合而不用担心索引问题,但这也是缺点。 foreach循环对象通常是集合、ArrayList、链接列表、向量和数组。

众所周知,集合中ArrayList的基础是以数组实现的,而擅长随机访问的链接列表的基础是以链表实现的,擅长顺序访问。

是自由交错器(forvs )

遍历数组和集合时,如果不需要使用下标,也可以使用foreach。 不能使用foreach修改数组或集合。 因为foreach中的元素指向的是副本,而不是数组或集合本身。 对于数组类型集合foreach,for循环遍历数组时需要确定数组的长度,引入自增量变量,每次检查自增量变量是否在范围内,然后在hash中查找元素,因此效率稍微高。 另一方面,在foreach循环中遍历数组时,指针会自动指向: 如果有,就不需要知道数组的长度和判断,但差距不是很大。 高一位。 请看照片1。 对于链表类型的集合,foreach的效率明显高于for。 链表适用于顺序访问,而foreach根据迭代程序规则一个接一个地访问,因此在数据量大的情况下存在一位以上的差异。 参照图2。 结果图1 :

ArrayList遍历1千万条数据的三种方法需要时间,for为29秒,foreach为27秒,一位,迭代器也为27秒。

图2 :

链接列表遍历50万条数据的三种方法需要时间,for用为1449秒,foreach用为1.3秒,完全不同。 迭代器为1.4秒。

代码包福克斯; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List;/* * * createdbyyangyouxing * date on 2017/6/2.*/publicclassfortest { publicstaticvoidprint (liststringlist ) for ) () i list.size (; I ()/list.get ) I; 系统. out.println (list.get (I ) ); } publicstaticvoidprint1(liststringlist ) for(strings:list ) system.out.println ) s; } publicstaticvoidprint2(liststringlist ) { iterator iterator=list.iterator ); wile(iterator.hasnext () ) { //iterator.next ); system.out.println (iterator.next ); } publicstaticliststringcreate (long num,boolean isLinkedList ) { ListString list; if (is链接列表(列表=新链接列表) ); } else { list=new ArrayList (; }for(intI=0; i num; I ) list.add(I ' ); }返回列表; } publicstaticvoidmain (字符串[ ] args ) ArrayList比较//test(1000000,false ); 遍历链接列表以测试(500000,true ); }隐私声明(长编号,布尔is链接列表) {字符串类型; 列表列表; if (is链接列表)列表=create (num,true ); 类型=' linked list '; }else{list=create(num,false ); 类型=' ArrayList '; //传统的for longa=system.current time millis (; 打印(列表; long b=System.currentTimeMillis (; //foreachlongc=system.current time millis (; 打印1 (列表); long d=System.currentTimeMillis (; //迭代器long e=System.currentTimeMillis (; 打印2 (列表); long f=System.currentTimeMillis (; system.out.println (类型' -传统的for循环需要时间((b - a ) ) ms ); system.out.println (type '-foreach循环需要时间() (d - c ) ) ms ); system.out.println (类型(-迭代器循环需要时间((f - e ) ) ms ); }

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。