如何使用自定义类为每个循环使用 java?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/975383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:46:54  来源:igfitidea点击:

How can I use the java for each loop with custom classes?

javaclassforeach

提问by Geo

I think most coders have used code like the following :

我认为大多数编码员都使用过如下代码:


ArrayList<String> myStringList = getStringList();
for(String str : myStringList)
{
   doSomethingWith(str);
}

How can I take advantage of the for each loop with my own classes? Is there an interface I should be implementing?

如何在我自己的类中利用 for each 循环?是否有我应该实现的接口?

采纳答案by Brian Agnew

You can implement Iterable.

您可以实现Iterable

Here's an example. It's not the best, as the object is its own iterator. However it should give you an idea as to what's going on.

这是一个例子。这不是最好的,因为对象是它自己的迭代器。但是,它应该让您了解正在发生的事情。

回答by Pierre

You have to implement the Iterable interface, that is to say, you have to implement the method

你要实现 Iterable接口,也就是说你要实现方法

class MyClass implements Iterable<YourType>
{
Iterator<YourType> iterator()
  {
  return ...;//an iterator over your data
  }
}

回答by Tombart

The short version of for loop (Tstands for my custom type):

for 循环的简短版本(T代表我的自定义类型):

for (T var : coll) {
    //body of the loop
}

is translated into:

被翻译成:

for (Iterator<T> iter = coll.iterator(); iter.hasNext(); ) {
    T var = iter.next();
    //body of the loop
}

and the Iterator for my collection might look like this:

我的集合的迭代器可能如下所示:

class MyCollection<T> implements Iterable<T> {

    public int size() { /*... */ }

    public T get(int i) { /*... */ }

    public Iterator<T> iterator() {
        return new MyIterator();
    }

    class MyIterator implements Iterator<T> {

        private int index = 0;

        public boolean hasNext() {
            return index < size();
        }

        public type next() {
            return get(index++);
        }

        public void remove() {
            throw new UnsupportedOperationException("not supported yet");

        }
   }
}