在同一个类中实现Java Iterator和Iterable? [英] Implement Java Iterator and Iterable in same class?

查看:139
本文介绍了在同一个类中实现Java Iterator和Iterable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试理解Java Iterator Iterable 接口

I am trying to understand Java Iterator and Iterable interfaces

我正在写这个类

class MyClass implements Iterable<String> {
    public String[] a = null;
    public MyClass(String[] arr) {
        a = arr;    
    }

    public MyClassIterator iterator() {
        return new MyClassIterator(this);
    }

    public class MyClassIterator implements Iterator<String> {
        private MyClass myclass = null;
        private int count = 0;
        public MyClassIterator(MyClass m) {
            myclass = m;    
        }

        public boolean hasNext() {
            return count < myclass.a.length;
        }
        public String next() {
            int t = count;
            count++;
            return myclass.a[t];
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }
    }   
}

似乎工作正常。

我应该:

Myclass implements Iterable<Stirng>, Iterator<String> {

}

或者我应该放 MyClassIterator MyClass as

Or I should put MyClassIterator outside MyClass as

class MyClass implements Iterable<String> {
    public String[] a = null;
    public MyClass(String[] arr) {
        a = arr;    
    }
    public MyClassIterator iterator() {
        return new MyClassIterator(this);
    }
}


    public class MyClassIterator implements Iterator<String> {
        private MyClass myclass = null;
        private int count = 0;
        public MyClassIterator(MyClass m) {
            myclass = m;    
        }

        public boolean hasNext() {
            return count < myclass.a.length;
        }
        public String next() {
            int t = count;
            count++;
            return myclass.a[t];
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }
    }   

哪一个更好?

推荐答案

你几乎永远不会同时实现 Iterable Iterator 在同一个班级。他们做不同的事情。迭代器自然是有状态的 - 当你使用它迭代时,它必须更新它的世界观。但是,迭代只需要能够创建新的迭代器。特别是,你可以让几个迭代器同时在相同的原始迭代上工作。

You should almost never implement both Iterable and Iterator in the same class. They do different things. An iterator is naturally stateful - as you iterate using it, it has to update its view of the world. An iterable, however, only needs to be able to create new iterators. In particular, you could have several iterators working over the same original iterable at the same time.

你当前的方法非常好 - 有一些方面的实现我' d改变,但在责任分离方面很好。

Your current approach is pretty much okay - there are aspects of the implementation I'd change, but it's fine in terms of the separation of responsibilities.

这篇关于在同一个类中实现Java Iterator和Iterable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆