集合遍历 java
jdk1.5以前对集合和数组的遍历 for(Iterator i=c.iterator();i.hasNext();){ dosomething((Element)i.next()); } for(int i=0;i<a.length;i++){ } jdk1.5之后 for(Element e:elements){}1.利用for-each不会有性能的损失,在某些状况下,比起普通的for循环,它还稍有性能优点,由于它对数组索引的边界值只计算一次。
2.在对多个集合进行嵌套迭代时,for-each循环相对应传统的for循环的这种优点会更加明显 数组
enum Face{one,two,three,four,five,six} Collection<Face> faces=new Arrays.asList(Face.values); for(Iterator<Face> i=faces.iterator;i.hasNext();) for(Iterator<Face> j=faces.iterator;j.hasNext();) system.out.println(i.next()+" "+j.next()); 程序不会抛出异常,但不会完成你的工做,这种bug很难发现若是使用for-each这个问题就彻底消失了
for(Face f1:faces) for(Face f2:faces) system.out.println(f1+""+f2);
有几种状况没法使用for-each 性能
1.替换:须要替换列表中的部分元素或所有元素 spa
List<String> test=new ArrayList<String>(); test.add("aa"); test.add("bb"); for(String s:test){ test.remove(s); test.add("New_aa");//ConcurrentModificationException }
for(int i=0;i<test.size();i++){ test.remove(i); test.add("new"); } //成功的替换
2.删除:若是要遍历,并删除指定的元素(并非当前遍历到的元素),就须要显示的迭代器 code
3.迭代若是须要并行的遍历多个集合,就须要显示的控制迭代器或者索引变量,以便全部迭代器或者索引变量获得同步前移 索引
如这段上面举例的问题代码
enum Face{one,two,three,four,five,six}
Collection<Face> faces=new Arrays.asList(Face.values);
for(Iterator<Face> i=faces.iterator;i.hasNext();)
for(Iterator<Face> j=faces.iterator;j.hasNext();)
system.out.println(i.next()+" "+j.next()); //获得同步前移