android 迭代器模式Iterator

    private void t() {
        myList myList = new myList();
        myList.add("one");
        myList.add("two");
        myList.add("three");
        myList.add("four");
        Iterator iterator = myList.iterator();
        while (iterator.hasNext())
        {
            Object next = iterator.next();
            Log.i(TAG, "t: "+next.toString());
        }
    }

    interface Iterator{
        boolean hasNext();
        Object next();
    }

    interface MapList{
        int size();
        Object get(int i);
        void add(Object o);
        void remove(Object o);
        Iterator iterator();
    }

    class MapIterator implements Iterator{

        MapList list;
        int index=-1;

        public MapIterator(MapList list) {
            this.list = list;
        }

        @Override
        public boolean hasNext() {
            return index<list.size();
        }

        @Override
        public Object next() {
            return list.get(++index);
        }
    }

    class myList implements MapList{

        List<Object> objects=new ArrayList<>();

        @Override
        public int size() {
            return objects.size();
        }

        @Override
        public Object get(int i) {
            return objects.get(i);
        }

        @Override
        public void add(Object o) {
            objects.add(o);
        }

        @Override
        public void remove(Object o) {
            objects.remove(o);
        }

        @Override
        public Iterator iterator() {
            return new MapIterator(this);
        }
    }
发布了179 篇原创文章 · 获赞 60 · 访问量 25万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览