深入了解 Java迭代器

来源:互联网 发布:网易音乐经典评论知乎 编辑:程序博客网 时间:2024/06/06 10:57

迭代器详解

[toc]



概念 :

迭代器(iterator)有时又称游标(cursor)是程序设计的软件设计模式,可在容器(container,例如链表或阵列>)上遍访的接口,设计人员无需关心容器的内容。
                                            ——–百度百科 点 击查看


简易容器

package club.dohacker.Demo;class MyList{    private String list[] = null; //先存放容纳String类型的容器    private int size = 0 ;       //表示容器中数据的多少    private static final int DEFAULT_SIZE = 10; //容器默认的大小是 10    public MyList(){        this(DEFAULT_SIZE);    }    public MyList(int size){        this.list = new String[size];    }    /**     * 添加数据容器元素     * @param elem     */    public void add(String elem){        //先判断扩容        if(this.list.length <= this.size){           String temp[] = new String[this.size*2+1];           System.arraycopy(this.list, 0, temp, 0, this.list.length);           this.list = temp;        }        this.list[this.size++] = elem;    }    /**     * 获取容器中的元素的个数     * @return int size     */    public int size(){        return this.size;    }    public String get(int index){        //判断范围        if(index<0 || index >=this.size){            try {                throw new Exception("访问元素越界异常");            } catch (Exception e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }        return this.list[index];    }}public class Demo1 {   public static void main(String[] args) {       //创建容器       MyList list = new MyList();       //添加元素       list.add("a");       list.add("b");       list.add("c");       list.add("d");       list.add("e");       //输出       System.out.println(list.size());       for(int i=0;i<list.size();i++){           System.out.println(list.get(i));       }   }}

简易迭代器 :

仅仅实现迭代器的功能
缺陷 : 一个容器对象的迭代器只能使用一次,使用新的迭代器需要创建一个新的容器
代码如下 :

package club.dohacker.Demo;class MyList{    public String list[] = null; //先存放容纳String类型的容器    private int size = 0 ;       //表示容器中数据的多少    private static final int DEFAULT_SIZE = 10; //容器默认的大小是 10    private int pre=-1;    //表示前驱游标    private int cursor = 0;//当前游标    public MyList(){        this(DEFAULT_SIZE);    }    public MyList(int size){        this.list = new String[size];    }    /**     * 添加数据容器元素     * @param elem     */    public void add(String elem){        //先判断扩容        if(this.list.length <= this.size){           String temp[] = new String[this.size*2+1];           System.arraycopy(this.list, 0, temp, 0, this.list.length);           this.list = temp;        }        this.list[this.size++] = elem;    }    /**     * 获取容器中的元素的个数     * @return int size     */    public int size(){        return this.size;    }    public String get(int index){        //判断范围        if(index<0 || index >=this.size){            try {                throw new Exception("访问元素越界异常");            } catch (Exception e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }        return this.list[index];    }     //下面是迭代器中的方法    /**      *判断是否有下一个元素       * @return      */    public boolean hasNext(){        return   (this.cursor >= (this.size-1))? false : true;    }    /**     * 获取下一个     */    public String next(){        if(hasNext()){          this.pre = cursor;          return this.list[++cursor];        }else{          return null;          }    }    /**     * 删除     */    public void remove(){        if(pre == -1 || this.size==0){            return ;        }        for(int i=pre;i<this.size-1;i++){            this.list[i] = this.list[i+1];        }      //只有一个元素的情况        this.cursor--;        this.pre = -1;        this.size--;    }}public class Demo1 {   public static void main(String[] args) {       //创建容器       MyList list = new MyList();       //添加元素       list.add("a");       list.add("b");       list.add("c");       list.add("d");       list.add("e");       //输出       System.out.println(list.size());       for(int i=0;i<list.size();i++){           System.out.println(list.get(i));       }       //使用迭代       System.out.println("迭代如下:\n");       while(list.hasNext()){           System.out.println(list.next());           list.remove();       }       System.out.println(list.size());   }}




加深迭代器:

  1. 解决迭代器只能使用一次的情况 , 使用匿名内部类,每次获取迭代器就是一个新的初始化的对象
  2. 增加泛型 :增加容器的兼容性
package club.dohacker.Demo;import club.dohacker.Demo.MyList.MyIterator;class MyList<T>{    public Object list[] = null; //先存放容纳String类型的容器    private int size = 0 ;       //表示容器中数据的多少    private static final int DEFAULT_SIZE = 10; //容器默认的大小是 10    public MyList(){        this(DEFAULT_SIZE);    }    public MyList(int size){        this.list = new Object[size];    }    /**     * 添加数据容器元素     * @param elem     */    public void add(T elem){        //先判断扩容        if(this.list.length <= this.size){           Object temp[] = new Object[this.size*2+1];           System.arraycopy(this.list, 0, temp, 0, this.list.length);           this.list = temp;        }        this.list[this.size++] = elem;    }    /**     * 获取容器中的元素的个数     * @return int size     */    public int size(){        return this.size;    }    @SuppressWarnings("unchecked")    public T get(int index){        //判断范围        if(index<0 || index >=this.size){            try {                throw new Exception("访问元素越界异常");            } catch (Exception e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }        return (T)this.list[index];    }    //获取迭代器    public MyIterator iterator(){        return new MyIterator();    }    class  MyIterator {         //下面是迭代器中的方法        private int pre=-1;    //表示前驱游标        private int cursor = 0;//当前游标        /**          *判断是否有下一个元素           * @return          */        public boolean hasNext(){            return   (this.cursor >= (MyList.this.size-1))? false : true;        }        /**         * 获取下一个         */        public T next(){            if(hasNext()){              this.pre = cursor;              return (T)MyList.this.list[++cursor];            }else{              return null;              }        }        /**         * 删除         */        public void remove(){            if(pre == -1 || MyList.this.size==0){                return ;            }            for(int i=pre;i<MyList.this.size-1;i++){                MyList.this.list[i] = MyList.this.list[i+1];            }          //只有一个元素的情况            this.cursor--;            this.pre = -1;            MyList.this.size--;        }    }}public class Demo1 {   public static void main(String[] args) {       //创建容器       MyList<String> list = new MyList<String>();       //添加元素       list.add("a");       list.add("b");       list.add("c");       list.add("d");       list.add("e");       //输出       System.out.println(list.size());       for(int i=0;i<list.size();i++){           System.out.println(list.get(i));       }       //使用迭代       System.out.println("迭代如下:\n");       MyIterator iterator = list.iterator();         while(iterator.hasNext()){           System.out.println(iterator.next());           iterator.remove();       }       System.out.println(list.size());   }}




可以使用foreach的迭代器

需要容器继承了iterable 接口就能使用了
修改成了匿名类的形式 , 因为迭代器就会在哪一个地方使用

package club.dohacker.Demo;import java.util.Iterator;class MyList<T> implements Iterable{    public Object list[] = null; //先存放容纳String类型的容器    private int size = 0 ;       //表示容器中数据的多少    private static final int DEFAULT_SIZE = 10; //容器默认的大小是 10    public MyList(){        this(DEFAULT_SIZE);    }    public MyList(int size){        this.list = new Object[size];    }    /**     * 添加数据容器元素     * @param elem     */    public void add(T elem){        //先判断扩容        if(this.list.length <= this.size){           Object temp[] = new Object[this.size*2+1];           System.arraycopy(this.list, 0, temp, 0, this.list.length);           this.list = temp;        }        this.list[this.size++] = elem;    }    /**     * 获取容器中的元素的个数     * @return int size     */    public int size(){        return this.size;    }    @SuppressWarnings("unchecked")    public T get(int index){        //判断范围        if(index<0 || index >=this.size){            try {                throw new Exception("访问元素越界异常");            } catch (Exception e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }        return (T)this.list[index];    }    //获取迭代器    public Iterator<T> iterator(){        return new Iterator<T>() {             //下面是迭代器中的方法            private int pre=-1;    //表示前驱游标            private int cursor = 0;//当前游标            /**              *判断是否有下一个元素               * @return              */            public boolean hasNext(){                return   (this.cursor >= (MyList.this.size))? false : true;            }            /**             * 获取下一个             */            public T next(){                if(hasNext()){                  this.pre = cursor;                  return (T)MyList.this.list[cursor++];                }else{                  return null;                  }            }            /**             * 删除             */            public void remove(){                if(pre == -1 || MyList.this.size==0){                    return ;                }                for(int i=pre;i<MyList.this.size-1;i++){                    MyList.this.list[i] = MyList.this.list[i+1];                }              //只有一个元素的情况                this.cursor--;                this.pre = -1;                MyList.this.size--;            }        };    }}public class Demo1 {   public static void main(String[] args) {       //创建容器       MyList<String> list = new MyList<String>();       //添加元素       list.add("a");       list.add("b");       list.add("c");       list.add("d");       list.add("e");       //输出       System.out.println(list.size());       for(int i=0;i<list.size();i++){           System.out.println(list.get(i));       }       //使用迭代       System.out.println("迭代如下:\n");       Iterator<String> iterator = list.iterator();         while(iterator.hasNext()){           System.out.println(iterator.next());       }       System.out.println(list.size());       System.out.println("使用for循环的效果如下:");       //使用foreach       for(Object obj : list){           System.out.println(obj.toString());       }   }}
原创粉丝点击