zoukankan      html  css  js  c++  java
  • java迭代器demo

    package cn.aust.zyw.demo;
    
    import java.util.Iterator;
    
    /**
     * Created by zyw on 2016/2/16.
     * Iterator模式是用于遍历集合类的标准访问方法。
     * 它可以把访问逻辑从不同类型的集合类中抽象出来,从而避免向客户端暴露集合的内部结构。
     * Store类继承Iterable接口,利用自定义的hasNext(),next()
     * 输出数组a的元素。
     */
    public class TestIterable {
        public static void main(String args[]){
            TestIterable testIterable=new TestIterable();
        }
        TestIterable(){
            Store store=new Store();
            System.out.println("************");
    
            for(String item:store){
                System.out.print(item+" ");
            }
    //        for(Iterator iter = store.iterator(); iter.hasNext();){
    //            System.out.print(iter.next()+" ");
    //        }
        }
    }
    class Store implements Iterable<String>{
        private   String a[]={"apple","orange","pear","banana"};
        @Override
        public Iterator<String> iterator() {
            return new Iterator<String>() {
                private int i=0;
                @Override
                public boolean hasNext() {//Returns true if the iteration has more elements
                    if(i<a.length){
                        return true;
                    }
                    return false;
                }
    
                @Override
                public String next() {//  Returns the next element in the iteration.
                    return a[i++];
                }
            };
        }
    }
  • 相关阅读:
    学习路线
    环境搭建时用到的文档
    商城技术重点分析
    svn 忽略文件
    实用的css3 学习笔记
    转载 《AngularJS》5个实例详解Directive(指令)机制
    php 单例设计模式 example
    html5 图片转base64预览显示
    curl返回常见错误码
    jquery的end(),addBack()方法example
  • 原文地址:https://www.cnblogs.com/yunwuzhan/p/5193961.html
Copyright © 2011-2022 走看看