46条for_each循环优于传统for循环

来源:互联网 发布:神奇百货ceo骗局 知乎 编辑:程序博客网 时间:2024/04/29 19:15

Jdk1.5之前,变量集合做法如下:

请去翻Effect Java原书。

比如:

public staticvoid main(String[] args) {

                   ArrayListarray = new ArrayList();

                   array.add("a");

                   array.add("b");

                   for(Iteratori = array.iterator(); i.hasNext(); ){

                            System.out.println(i.next());

                   }

         }

遍历数组就是我们常用的如下:

请去翻Effect Java原书。

 

这两种做法比while要好,避免了复制粘贴的错误,但是还不够完美,迭代器和索引变量会造成一些混乱。如果出现超过三次就很容易出错。

Jdk1.5之后,音符for-each循环,适用于集合和数组

性能上没有损失,推荐我们使用,肯定是有原因的:

文中举了两个例子:请去翻Effect Java原书。

(1)      嵌套遍历两个结合,产生m*n的结果的时候,我们会很容易使用如下:

Dosomething(i.netx(),j.next());

这样就会有bug,我们应该定义一个变量 temp=i.next();在遍历另一个

(2)      打印两个筛子的36种情况,也会出现类似的问题

这就是为什么要使用for-each,一个呢是,代码优雅,更重要的是可以直接避免我们自以为是的错误。

最后,文中说,如果我们自己编写的类型表示一组元素,即使不实现Collection也要实现Iterable接口。

一般的类是差不多这个样子:

class Model implementsIterable<String>{

         ArrayList<String>list = new ArrayList<String>();

         public  void add(String str) {

                   list.add(str);

         }

         @Override

         publicIterator<String> iterator() {

                   returnlist.iterator();

         }

        

}

然后这么用:

Model model = new Model();

                   model.add("c");

                   model.add("d");

                   for(Strings:model){

                            System.out.println(s);

                   }

不如实际使用ArrayList了,可能是Model类中如果还有其他的东西,比如一个班级,有自己的班级号classNum,学生数studentNum,然后才是studentList。这个问题值得研究,应该是有别的原因的。

http://huxiao.iteye.com/blog/867752。该博客这么写参考了ArrayList的源码的写法,自己看看,大家可以讨论学习。

 

那么问题来了,IterableIterator的区别

Java api文档这么说的:在java.util包中

public interface Iterator<E>

An iterator over a collection. Iterator takesthe place of Enumeration inthe Java Collections Framework. Iterators differ from enumerations in two ways:

  • Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
  • Method names have been improved.

This interface is a member of the Java Collections Framework.

 

Iterator遍历一个集合,在java集合框架中取代了枚举,和枚举有两点不同:

     允许调用者删除元素,不理解具体的使用情形

     方法名称得到改善,不理解。这个应该是和枚举的方法名称比,更合理,容易理解

它是java集合框架的一个成员java集合框架还是需要学习,阅读其官方文档。(进入ArrayList等,找到This class is a member of the Java CollectionsFramework.点击有时间看吧)。

 

Iterable 在java.lang包中,就一句话说明,也只有一个方法

public interface Iterable<T>

Implementing this interface allows anobject to be the target of the "foreach" statement.

 

 

一个总结的比较好的;原文:http://blog.csdn.net/ningguixin/article/details/8079242

Iterator是迭代器类,而Iterable是接口。 
好多类都实现了Iterable接口,这样对象就可以调用iterator()方法。 
一般都是结合着用,比如 
HashMap类就实现了Iterable接口,而要访问或打印出Map中所有内容时,就可以这样: HashMap hashMap; 
Iterator iter = hashMap.iterator(); 
while(iter.hashNext()) { 
  String s = iter.next(); 



为什么一定要实现Iterable接口,为什么不直接实现Iterator接口呢? 
      看一下JDK中的集合类,比如List一族或者Set一族,都是实现了Iterable接口,但并不直接实现Iterator接口。 
仔细想一下这么做是有道理的。 

      因为Iterator接口的核心方法next()或者hasNext() 是依赖于迭代器的当前迭代位置的。 
      如果Collection直接实现Iterator接口,势必导致集合对象中包含当前迭代位置的数据(指针)。 
      当集合在不同方法间被传递时,由于当前迭代位置不可预置,那么next()方法的结果会变成不可预知。 
      除非再为Iterator接口添加一个reset()方法,用来重置当前迭代位置。 
      但即时这样,Collection也只能同时存在一个当前迭代位置。 
      Iterable则不然,每次调用都会返回一个从头开始计数的迭代器。 
      多个迭代器是互不干扰的。 

0 0