迭代器和可迭代器有什么区别以及如何使用它们?

发布于 2024-11-27 02:43:16 字数 50 浏览 1 评论 0原文

我是 Java 新手,我真的对迭代器和可迭代感到困惑。谁能给我解释一下并举一些例子吗?

I am new in Java and I'm really confused with iterator and iterable. Can anyone explain to me and give some examples?

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

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

发布评论

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

评论(15

森末i 2024-12-04 02:43:16

Iterable 是一系列可迭代元素的简单表示。它没有任何迭代状态,例如“当前元素”。相反,它有一种生成 Iterator 的方法。

Iterator 是具有迭代状态的对象。它允许您使用 hasNext() 检查是否有更多元素,并使用 next() 移动到下一个元素(如果有)。

通常,Iterable 应该能够生成任意数量的有效Iterator

An Iterable is a simple representation of a series of elements that can be iterated over. It does not have any iteration state such as a "current element". Instead, it has one method that produces an Iterator.

An Iterator is the object with iteration state. It lets you check if it has more elements using hasNext() and move to the next element (if any) using next().

Typically, an Iterable should be able to produce any number of valid Iterators.

零時差 2024-12-04 02:43:16

Iterable 的实现是提供自身的 Iterator 的实现:

public interface Iterable<T>
{
    Iterator<T> iterator();
}

迭代器是一种简单的方法,允许某些人在没有分配权限的情况下循环访问数据集合(尽管具有能力)删除)。

public interface Iterator<E>
{
    boolean hasNext();
    E next();
    void remove();
}

请参阅 Javadoc

An implementation of Iterable is one that provides an Iterator of itself:

public interface Iterable<T>
{
    Iterator<T> iterator();
}

An iterator is a simple way of allowing some to loop through a collection of data without assignment privileges (though with ability to remove).

public interface Iterator<E>
{
    boolean hasNext();
    E next();
    void remove();
}

See Javadoc.

烟雨扶苏 2024-12-04 02:43:16

我将以 ArrayList 为例来回答这个问题,以帮助您更好地理解。Iterable

  1. 接口强制其子类实现抽象方法“iterator()”。
公共接口可迭代{
  ...
  抽象迭代器迭代器(); //返回 T 类型元素上的“迭代器”(不是迭代器)。
  ...
}
  1. 迭代器接口强制其子类实现抽象方法“hasNext()”和“next()”。
公共接口迭代器 {
  ...
  抽象布尔值 h​​asNext(); //如果迭代有更多元素,则返回 true。
  抽象 E next(); //返回迭代中的下一个元素。
  ...
}
  1. ArrayList 实现了 List,List 扩展了 Collection,Collection 扩展了 Iterable。
    也就是说,你可以看到这样的关系

    <块引用>

    'Iterable <- Collection <- List <- ArrayList'


Iterable、Collection 和 List 只是声明了抽象方法“iterator()”,而 ArrayList 单独实现了它。

  1. 我将使用“iterator()”方法显示 ArrayList 源代码,如下所示,以获取更多详细信息。

“iterator()”方法返回一个实现“Iterator”的类“Itr”的对象。

public class ArrayList; ...实现List,...
{
  ...
  公共迭代器迭代器(){
              返回新的 Itr();
  }


  私有类 Itr 实现 Iterator {
          ...

          公共布尔 hasNext() {
              返回光标!=大小;
          }
          @SuppressWarnings(“未选中”)
          公共E下一个(){
              checkForCommodification();
              int i = 光标;
              if (i >= 大小)
                  抛出新的NoSuchElementException();
              Object[] elementData = ArrayList.this.elementData;
              if (i >= elementData.length)
                  抛出新的 ConcurrentModificationException();
              光标 = i + 1;
              返回 (E) elementData[lastRet = i];
          }
          ...
  }
}
  1. 其他一些方法或类将通过使用 Iterator (Itr) 来迭代集合(如 ArrayList)的元素。

这是一个简单的例子。

public static void main(String[] args) {

    List<String> list = new ArrayList<>();
    list.add("a");
    list.add("b");
    list.add("c");
    list.add("d");
    list.add("e");
    list.add("f");

    Iterator<String> iterator = list.iterator();
    while (iterator.hasNext()) {
        String string = iterator.next();
        System.out.println(string);
    }
}

现在,清楚了吗? :)

I will answer the question especially about ArrayList as an example in order to help you understand better..

  1. Iterable interface forces its subclasses to implement abstract method 'iterator()'.
public interface Iterable {
  ...
  abstract Iterator<T> iterator(); //Returns an 'Iterator'(not iterator) over elements of type T.
  ...
}
  1. Iterator interface forces its subclasses to implement abstract method 'hasNext()' and 'next()'.
public interface Iterator {
  ...
  abstract boolean hasNext(); //Returns true if the iteration has more elements.
  abstract E next();          //Returns the next element in the iteration.
  ...
}
  1. ArrayList implements List, List extends Collection and Collection extends Iterable..
    That is, you could see the relationship like

    'Iterable <- Collection <- List <- ArrayList'

.
And Iterable, Collection and List just declare abstract method 'iterator()' and ArrayList alone implements it.

  1. I am going to show ArrayList source code with 'iterator()' method as follows for more detailed information.

'iterator()' method returns an object of class 'Itr' which implements 'Iterator'.

public class ArrayList<E> ... implements List<E>, ...
{
  ...
  public Iterator<E> iterator() {
              return new Itr();
  }


  private class Itr implements Iterator<E> {
          ...

          public boolean hasNext() {
              return cursor != size;
          }
          @SuppressWarnings("unchecked")
          public E next() {
              checkForComodification();
              int i = cursor;
              if (i >= size)
                  throw new NoSuchElementException();
              Object[] elementData = ArrayList.this.elementData;
              if (i >= elementData.length)
                  throw new ConcurrentModificationException();
              cursor = i + 1;
              return (E) elementData[lastRet = i];
          }
          ...
  }
}
  1. Some other methods or classes will iterate elements of collections like ArrayList through making use of Iterator (Itr).

Here is a simple example.

public static void main(String[] args) {

    List<String> list = new ArrayList<>();
    list.add("a");
    list.add("b");
    list.add("c");
    list.add("d");
    list.add("e");
    list.add("f");

    Iterator<String> iterator = list.iterator();
    while (iterator.hasNext()) {
        String string = iterator.next();
        System.out.println(string);
    }
}

Now, is it clear? :)

胡大本事 2024-12-04 02:43:16

我知道这是一个老问题,但是对于任何读到这篇文章的人来说,如果他们遇到同样的问题,并且可能对所有术语感到不知所措,这里有一个很好的、简单的类比,可以帮助您理解迭代器和迭代器之间的区别

:公共图书馆。老派。与纸质书。是的,就是那种图书馆。

装满书的书架就像是一个可迭代对象。可以看到书架上排着长长的一排书。你可能不知道有多少本,但你可以看出,这是一本很长的藏书。

图书管理员就像迭代器。他可以随时指出一本特定的书。他可以在他指向的位置插入/删除/修改/阅读该书。每次你喊“下一本!”时,他都会按顺序一次指向每一本书。给他。所以,你通常会问他:“有下一个吗?”,他会说“是”,你说“下一个!”他会指着下一本书。他还知道什么时候到达了书架的末尾,因此当你问:“有下一个吗?”他会说“不”。

我知道这有点傻,但我希望这会有所帮助。

I know this is an old question, but for anybody reading this who is stuck with the same question and who may be overwhelmed with all the terminology, here's a good, simple analogy to help you understand this distinction between iterables and iterators:

Think of a public library. Old school. With paper books. Yes, that kind of library.

A shelf full of books would be like an iterable. You can see the long line of books in the shelf. You may not know how many, but you can see that it is a long collection of books.

The librarian would be like the iterator. He can point to a specific book at any moment in time. He can insert/remove/modify/read the book at that location where he's pointing. He points, in sequence, to each book at a time every time you yell out "next!" to him. So, you normally would ask him: "has Next?", and he'll say "yes", to which you say "next!" and he'll point to the next book. He also knows when he's reached the end of the shelf, so that when you ask: "has Next?" he'll say "no".

I know it's a bit silly, but I hope this helps.

等风来 2024-12-04 02:43:16

如果集合是可迭代的,则可以使用迭代器对其进行迭代(因此可以在 foreach 循环中使用)。迭代器是将迭代集合的实际对象。

If a collection is iterable, then it can be iterated using an iterator (and consequently can be used in a for each loop.) The iterator is the actual object that will iterate through the collection.

甜妞爱困 2024-12-04 02:43:16

实现 Iterable 接口允许对象成为“foreach”语句的目标。

class SomeClass implements Iterable<String> {}

class Main 
{
  public void method()
  {
     SomeClass someClass = new SomeClass();
     .....

    for(String s : someClass) {
     //do something
    }
  }
}

迭代器是一个接口,它具有迭代元素的实现。 Iterable是一个提供Iterator的接口。

Implementing Iterable interface allows an object to be the target of the "foreach" statement.

class SomeClass implements Iterable<String> {}

class Main 
{
  public void method()
  {
     SomeClass someClass = new SomeClass();
     .....

    for(String s : someClass) {
     //do something
    }
  }
}

Iterator is an interface, which has implementation for iterate over elements. Iterable is an interface which provides Iterator.

-残月青衣踏尘吟 2024-12-04 02:43:16

最重要的考虑因素是所讨论的项目是否应该能够被遍历多次。这是因为您始终可以通过再次调用 iterator() 来倒回 Iterable,但无法倒回 Iterator。

The most important consideration is whether the item in question should be able to be traversed more than once. This is because you can always rewind an Iterable by calling iterator() again, but there is no way to rewind an Iterator.

已下线请稍等 2024-12-04 02:43:16

如上所述 这里,引入了“Iterable”以便能够在foreach循环中使用。实现了 Iterable 接口的类可以被迭代。

Iterator 是管理 Iterable 迭代的类。它维护当前迭代中所处的状态,并知道下一个元素是什么以及如何获取它。

As explained here, The “Iterable” was introduced to be able to use in the foreach loop. A class implementing the Iterable interface can be iterated over.

Iterator is class that manages iteration over an Iterable. It maintains a state of where we are in the current iteration, and knows what the next element is and how to get it.

岁月蹉跎了容颜 2024-12-04 02:43:16

考虑一个有 10 个苹果的例子。
当它实现Iterable时,就像将每个苹果放入从1到10的盒子中,并返回一个可用于导航的迭代器。

通过实现迭代器,我们可以获取任何苹果,下一个框中的苹果等。

因此,实现 iterable 可以提供一个迭代器来导航其元素,尽管要导航,需要实现迭代器。

Consider an example having 10 apples.
When it implements Iterable, it is like putting each apple in boxes from 1 to 10 and return an iterator which can be used to navigate.

By implementing iterator, we can get any apple, apple in next boxes etc.

So implementing iterable gives an iterator to navigate its elements although to navigate, iterator needs to be implemented.

彩虹直至黑白 2024-12-04 02:43:16

问题:Iterable 和 Iterator 之间的区别?
Ans:

iterable:与forEach循环有关
iterator:是与 Collection 相关的

forEach 循环的目标元素应该是可迭代的。
Collection Iterable中一一获取对象

我们可以使用Iterator从java.ḷang包中的
java.util 包中存在的迭代器

仅包含一种方法 iterator()
包含三个方法 hasNext()、next()、remove()

1.5版本引入
1.2版本引入

Question:Difference between Iterable and Iterator?
Ans:

iterable: It is related to forEach loop
iterator: Is is related to Collection

The target element of the forEach loop shouble be iterable.
We can use Iterator to get the object one by one from the Collection

Iterable present in java.ḷang package
Iterator present in java.util package

Contains only one method iterator()
Contains three method hasNext(), next(), remove()

Introduced in 1.5 version
Introduced in 1.2 version

丿*梦醉红颜 2024-12-04 02:43:16

基本上来说,两者的关系非常密切。

Iterator视为一个接口,它可以帮助我们借助一些未定义的方法(例如hasNext()、next()和remove())遍历集合

。另一方面,Iterable 是另一个接口,如果由类实现,则强制该类成为 Iterable,并且是 For-Each 构造的目标。
它只有一个名为 iterator() 的方法,该方法来自 Iterator 接口本身。

当集合是可迭代的时,就可以使用迭代器对其进行迭代。

如需了解,请访问这些:

可迭代: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Iterable.java

迭代器 http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Iterator.java

Basically speaking, both of them are very closely related to each other.

Consider Iterator to be an interface which helps us in traversing through a collection with the help of some undefined methods like hasNext(), next() and remove()

On the flip side, Iterable is another interface, which, if implemented by a class forces the class to be Iterable and is a target for For-Each construct.
It has only one method named iterator() which comes from Iterator interface itself.

When a collection is iterable, then it can be iterated using an iterator.

For understanding visit these:

ITERABLE: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Iterable.java

ITERATOR http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Iterator.java

瑾兮 2024-12-04 02:43:16

Iterable 被引入用于 java 中的每个循环。

public interface Collection<E> extends Iterable<E>  

Iterator 是管理 Iterable 迭代的类。它维护当前迭代中所处的状态,并知道下一个元素是什么以及如何获取它。

Iterable were introduced to use in for each loop in java

public interface Collection<E> extends Iterable<E>  

Iterator is class that manages iteration over an Iterable. It maintains a state of where we are in the current iteration, and knows what the next element is and how to get it.

つ低調成傷 2024-12-04 02:43:16

除了 ColinDSeeker回答。

简单来说,IterableIterator都是Java的Collection Framework中提供的接口。

Iterable

如果一个类想要有一个 for-each 循环来迭代它的集合,那么它必须实现 Iterable 接口。但是,for-each 循环只能用于向前循环集合,并且您将无法修改此集合中的元素。但是,如果您想要的只是读取元素数据,那么这非常简单,并且由于 Java lambda 表达式,它通常是一个行。例如:

iterableElements.forEach (x -> System.out.println(x) );

Iterator

此接口使您能够迭代集合,获取和删除其元素。每个集合类都提供一个 iterator() 方法,该方法将迭代器返回到集合的开头。与可迭代相比,此接口的优点在于,使用此接口您可以添加、修改或删除集合中的元素。但是,访问元素需要比可迭代元素多一点的代码。例如:

for (Iterator i = c.iterator(); i.hasNext(); ) {
       Element e = i.next();    //Get the element
       System.out.println(e);    //access or modify the element
}

来源:

  1. Java 文档迭代器
  2. Java 文档迭代器

In addition to ColinD and Seeker answers.

In simple terms, Iterable and Iterator are both interfaces provided in Java's Collection Framework.

Iterable

A class has to implement the Iterable interface if it wants to have a for-each loop to iterate over its collection. However, the for-each loop can only be used to cycle through the collection in the forward direction and you won't be able to modify the elements in this collection. But, if all you want is to read the elements data, then it's very simple and thanks to Java lambda expression it's often one liner. For example:

iterableElements.forEach (x -> System.out.println(x) );

Iterator

This interface enables you to iterate over a collection, obtaining and removing its elements. Each of the collection classes provides a iterator() method that returns an iterator to the start of the collection. The advantage of this interface over iterable is that with this interface you can add, modify or remove elements in a collection. But, accessing elements needs a little more code than iterable. For example:

for (Iterator i = c.iterator(); i.hasNext(); ) {
       Element e = i.next();    //Get the element
       System.out.println(e);    //access or modify the element
}

Sources:

  1. Java Doc Iterable
  2. Java Doc Iterator
乞讨 2024-12-04 02:43:16

匿名类可以轻松地将 Iterator 转换为 Iterable,并允许您使用 Iterable 语法(for 循环、forEach())。

示例:考虑一个 Iteratorit

for (T element : new Iterable<T>() {

    @Override
    public Iterator<T> iterator() {
        return it;
    }

}) {
    //do something with `T element`
}

抽象为函数

static <T> Iterable<T> toIterable(Iterator<T> it) {
    return new Iterable<T>() {

        @Override
        public Iterator<T> iterator() {
            return it;
        }

    };
}

用法

for (T element: toIterable(it) {
...
}

An anonymous class easily converts an Iterator to an Iterable and lets you use the Iterable syntax (for loops, forEach()).

Example: consider an Iterator<T> it

for (T element : new Iterable<T>() {

    @Override
    public Iterator<T> iterator() {
        return it;
    }

}) {
    //do something with `T element`
}

Abstracted in a function

static <T> Iterable<T> toIterable(Iterator<T> it) {
    return new Iterable<T>() {

        @Override
        public Iterator<T> iterator() {
            return it;
        }

    };
}

Usage

for (T element: toIterable(it) {
...
}
丑疤怪 2024-12-04 02:43:16

大多数 Java 接口以 'able' 结尾。例如IterableCloneableSerializedRunnable等。因此,Iterable是一个接口,有一个名为 iterator() 的抽象方法,该方法返回一个 Iterator 对象。

public interface Iterable {
  abstract Iterator<T> iterator(); 
}

迭代器接口具有抽象方法“hasNext()”和“next()”。

public interface Iterator {
 abstract boolean hasNext();
 abstract E next();          
}

一个明确的用途是 List 扩展 -> Collections Interface -> 扩展 Iterable
输入图片此处描述

List<String> countrylist = new ArrayList<>();
list.add("US");
list.add("China");
list.add("Japan");
list.add("India");

Iterator<String> it = countrylist.iterator();
while (it.hasNext()) {
    String string = it.next();
    System.out.println(string);
}

Most java interfaces ends with 'able'. examples are Iterable, Cloneable, Serializable, Runnable, etc. Therefore, Iterable is an interface that has an abstract method called iterator() which returns an Iterator object.

public interface Iterable {
  abstract Iterator<T> iterator(); 
}

Iterator interface has abstract method 'hasNext()' and 'next()'.

public interface Iterator {
 abstract boolean hasNext();
 abstract E next();          
}

A clear use is a List which extends->Collections Interface->extends Iterable
enter image description here

List<String> countrylist = new ArrayList<>();
list.add("US");
list.add("China");
list.add("Japan");
list.add("India");

Iterator<String> it = countrylist.iterator();
while (it.hasNext()) {
    String string = it.next();
    System.out.println(string);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文