在同一个类中实现 Java Iterator 和 Iterable?

发布于 2024-11-03 20:03:01 字数 1912 浏览 4 评论 0原文

我正在尝试理解 Java IteratorIterable 接口,

我正在编写这个类,

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 之外,因为

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();
        }
    }   

哪个更好?

I am trying to understand Java Iterator and Iterable interfaces

I am writing this class

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();
        }
    }   
}

It seems to be working.

Should I have:

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

}

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();
        }
    }   

Which one is better?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

人海汹涌 2024-11-10 20:03:01

您几乎永远不应该在同一个类中同时实现IterableIterator。他们做不同的事情。迭代器自然是有状态的 - 当您迭代使用它时,它必须更新其世界观。然而,可迭代对象只需要能够创建新的迭代器。特别是,您可以让多个迭代器同时处理同一个原始可迭代对象。

您当前的方法非常好 - 我会更改实现的某些方面,但在职责分离方面很好。

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.

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.

骷髅 2024-11-10 20:03:01

您的第一次尝试就已步入正轨。 MyClass 只需要实现 Iterable,而这又需要您提供 Iterator 实现来从 返回可迭代.iterator()

无需将 MyClassIterator 放在 MyClass 之外,因为在大多数情况下,您甚至不需要直接使用 Iterator (它是由 Iterable上的 for .. in .. 语法隐式使用),并且在所有其他情况下,接口就足够了,除非您实际上向实施(您可能永远不需要这样做)。

这是我的做法,请参阅内嵌的评论:

import java.util.Iterator;

class MyClass implements Iterable<String>{
    public String[] a=null; //make this final if you can
    public MyClass(String[] arr){
        a=arr; //maybe you should copy this array, for fear of external modification
    }

    //the interface is sufficient here, the outside world doesn't need to know
    //about your concrete implementation.
    public Iterator<String> iterator(){
        //no point implementing a whole class for something only used once
        return new Iterator<String>() {
            private int count=0;
            //no need to have constructor which takes MyClass, (non-static) inner class has access to instance members
            public boolean hasNext(){
                //simplify
                return count < a.length;
            }
            public String next(){
                return a[count++]; //getting clever
            }

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

You were on track with your first try. MyClass only needs to implement Iterable<String>, which in turn requires you to provide an Iterator<String> implementation to return from Iterable<String>.iterator().

There's no need to put the MyClassIterator outside of MyClass because in most cases you will never even need to directly use the Iterator<String> (it's used implicitly by the for .. in .. syntax on Iterable<String>s), and in all other cases the interface is sufficient unless you actually add additional behavior to the implementation (which you likely won't ever need to do).

Here's how I'd do it, see comments inlined:

import java.util.Iterator;

class MyClass implements Iterable<String>{
    public String[] a=null; //make this final if you can
    public MyClass(String[] arr){
        a=arr; //maybe you should copy this array, for fear of external modification
    }

    //the interface is sufficient here, the outside world doesn't need to know
    //about your concrete implementation.
    public Iterator<String> iterator(){
        //no point implementing a whole class for something only used once
        return new Iterator<String>() {
            private int count=0;
            //no need to have constructor which takes MyClass, (non-static) inner class has access to instance members
            public boolean hasNext(){
                //simplify
                return count < a.length;
            }
            public String next(){
                return a[count++]; //getting clever
            }

            public void remove(){
                throw new UnsupportedOperationException();
            }
        };
    }
}
晚雾 2024-11-10 20:03:01

您不应该执行 Myclass Implements Iterable,Iterator{ 因为迭代器是一次性的。除了列表迭代器之外,没有办法将它们返回到开头。

顺便说一句,您可以跳过

MyClass myClass;
public MyClassInterator(MyClass m){
  myclass=m;  
}

and 而不是引用引用

myClass

MyClass.this

的内部类不是静态的,因此 MyClass.this 将引用创建它的封闭类的实例。

You should not do Myclass implements Iterable<String>,Iterator<String>{ since iterators are single-use. With the exception of list iterators, there's no way to return them to the start.

Incidentally, you can skip the

MyClass myClass;
public MyClassInterator(MyClass m){
  myclass=m;  
}

and instead of referencing

myClass

reference

MyClass.this

Your inner class is not static, so MyClass.this will reference the instance of the enclosing class that created it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文