Java 中的 Iterator 接口有什么好处?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/89891/
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 08:10:28  来源:igfitidea点击:

What are the benefits of the Iterator interface in Java?

javaoopcollectionsinterfaceiterator

提问by user17182

I just learned about how the Java Collections Framework implements data structures in linked lists. From what I understand, Iteratorsare a way of traversing through the items in a data structure such as a list. Why is this interface used? Why are the methods hasNext(), next()and remove()not directly coded to the data structure implementation itself?

我刚刚了解了 Java Collections Framework 如何实现链表中的数据结构。据我所知,Iterators是一种遍历数据结构(如列表)中的项目的方法。为什么要使用这个接口?为什么方法是hasNext()next()remove()不是直接编码到数据结构实现本身?

From the Java website: link text

来自 Java 网站:链接文本

public interface Iterator<E>

An iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework. Iterators differ from enumerations in two ways:

  • Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
  • Method names have been improved.
This interface is a member of the Java Collections Framework.

公共接口 Iterator<E>

集合上的迭代器。迭代器取代了 Java 集合框架中的枚举。迭代器在两个方面不同于枚举:

  • 迭代器允许调用者在具有明确定义语义的迭代期间从底层集合中删除元素。
  • 方法名称已得到改进。
此接口是 Java 集合框架的成员。

I tried googling around and can't seem to find a definite answer. Can someone shed some light on why Sun chose to use them? Is it because of better design? Increased security? Good OO practice?

我试着用谷歌搜索,似乎找不到明确的答案。有人可以解释为什么 Sun 选择使用它们吗?是因为更好的设计吗?增加安全性?良好的面向对象实践?

Any help will be greatly appreciated. Thanks.

任何帮助将不胜感激。谢谢。

采纳答案by Dustman

Why is this interface used?

为什么要使用这个接口?

Because it supports the basic operations that would allow a client programmer to iterate over any kind of collection (note: not necessarily a Collectionin the Objectsense).

因为它支持允许客户端程序员迭代任何类型的集合的基本操作(注意:CollectionObject某种意义上不一定是 a )。

Why are the methods... not directly coded to the data structure implementation itself?

为什么方法......没有直接编码到数据结构实现本身?

They are, they're just marked Private so you can't reach into them and muck with them. More specifically:

他们是,他们只是被标记为私人,所以你不能接触他们并与他们混在一起。进一步来说:

  • You can implement or subclass an Iteratorsuch that it does something the standard ones don't do, without having to alter the actual object it iterates over.
  • Objects that can be traversed over don't need to have their interfaces cluttered up with traversal methods, in particular any highly specialized methods.
  • You can hand out Iteratorsto however many clients you wish, and each client may traverse in their own time, at their own speed.
  • Java Iteratorsfrom the java.util package in particular will throw an exception if the storage that backs them is modified while you still have an Iteratorout. This exception lets you know that the Iteratormay now be returning invalid objects.
  • 您可以实现或子类化 anIterator使其执行标准操作不执行的操作,而无需更改它迭代的实际对象。
  • 可以遍历的对象不需要让它们的接口被遍历方法弄得乱七八糟,尤其是任何高度专业化的方法。
  • 您可以分Iterators发给任意数量的客户,每个客户都可以按照自己的时间、自己的速度穿越。
  • Iterators如果支持它们的存储被修改而你仍然有一个Iteratorout ,那么 java.util 包中的Java将抛出异常。此异常让您知道Iterator现在可能返回无效对象。

For simple programs, none of this probably seems worthwhile. The kind of complexity that makes them useful will come up on you quickly, though.

对于简单的程序,这些似乎都不值得。但是,使它们有用的复杂性很快就会出现在您身上。

回答by Jason Punyon

Well it seems like the first bullet point allows for multi-threaded (or single threaded if you screw up) applications to not need to lock the collection for concurrency violations. In .NET for example you cannot enumerate and modify a collection (or list or any IEnumerable) at the same time without locking or inheriting from IEnumerable and overriding methods (we get exceptions).

好吧,似乎第一个要点允许多线程(或单线程,如果你搞砸了)应用程序不需要锁定并发冲突的集合。例如,在 .NET 中,如果不锁定或继承 IEnumerable 和覆盖方法(我们会遇到异常),则无法同时枚举和修改集合(或列表或任何 IEnumerable)。

回答by user11087

An interesting paper discussing the pro's and con's of using iterators:

一篇讨论使用迭代器的利弊的有趣论文:

http://www.sei.cmu.edu/pacc/CBSE5/Sridhar-cbse5-final.pdf

http://www.sei.cmu.edu/pacc/CBSE5/Sridhar-cbse5-final.pdf

回答by Alex Argo

I think it is just good OO practice. You can have code that deals with all kinds of iterators, and even gives you the opportunity to create your own data structures or just generic classes that implement the iterator interface. You don't have to worry about what kind of implementation is behind it.

我认为这只是很好的面向对象实践。您可以拥有处理各种迭代器的代码,甚至让您有机会创建自己的数据结构或仅实现迭代器接口的泛型类。您不必担心它背后的实现是什么样的。

回答by Arthur Thomas

Iterator simply adds a common way of going over a collection of items. One of the nice features is the i.remove() in which you can remove elements from the list that you are iterating over. If you just tried to remove items from a list normally it would have weird effects or throw and exception.

迭代器只是添加了一种遍历项目集合的常用方法。其中一项不错的功能是 i.remove(),您可以在其中从正在迭代的列表中删除元素。如果您只是尝试从列表中正常删除项目,则会产生奇怪的效果或抛出和异常。

The interface is like a contract for all things that implement it. You are basically saying.. anything that implements an iterator is guaranteed to have these methods that behave the same way. You can also use it to pass around iterator types if that is all you care about dealing with in your code. (you might not care what type of list it is.. you just want to pass an Iterator) You could put all these methods independently in the collections but you are not guaranteeing that they behave the same or that they even have the same name and signatures.

接口就像是所有实现它的东西的契约。你基本上是在说..任何实现迭代器的东西都保证有这些方法的行为方式相同。您还可以使用它来传递迭代器类型,如果这是您在代码中处理的全部内容。(你可能不关心它是什么类型的列表......你只是想传递一个迭代器)你可以将所有这些方法独立地放在集合中,但你不能保证它们的行为相同或者它们甚至具有相同的名称和签名。

回答by 64BitBob

Because you may be iterating over something that's not a data structure. Let's say I have a networked application that pulls results from a server. I can return an Iterator wrapper around those results and stream themthrough any standard code that accepts an Iterator object.

因为您可能正在迭代一些不是数据结构的东西。假设我有一个从服务器获取结果的网络应用程序。我可以围绕这些结果返回一个 Iterator 包装器,并通过任何接受 Iterator 对象的标准代码流式传输它们

Think of it as a key part of a good MVC design. The data has to get from the Model (i.e. data structure) to the View somehow. Using an Iterator as a go-between ensures that the implementation of the Model is never exposed. You could be keeping a LinkedList in memory, pulling information out of a decryption algorithm, or wrapping JDBC calls. It simply doesn't matter to the view, because the view only cares about the Iterator interface.

将其视为良好 MVC 设计的关键部分。数据必须以某种方式从模型(即数据结构)到视图。使用迭代器作为中间人可确保永远不会公开模型的实现。您可以将 LinkedList 保存在内存中,从解密算法中提取信息,或者包装 JDBC 调用。它与视图无关,因为视图只关心 Iterator 接口。

回答by chickeninabiscuit

Just M2C, if you weren't aware: you can avoid directly using the iterator interface in situations where the for-eachloop will suffice.

只是 M2C,如果您不知道:在for-each循环就足够的情况下,您可以避免直接使用迭代器接口。

回答by zxcv

Iterators are one of the many design patterns available in java. Design patterns can be thought of as convenient building blocks, styles, usage of your code/structure.

迭代器是 Java 中可用的众多设计模式之一。设计模式可以被认为是方便的构建块、样式、代码/结构的使用。

To read more about the Iterator design pattern check out the this website that talks about Iterator as well as many other design patterns. Here is a snippet from the site on Iterator: http://www.patterndepot.com/put/8/Behavioral.html

要阅读有关迭代器设计模式的更多信息,请查看有关迭代器以及许多其他设计模式的网站。以下是 Iterator 网站的片段:http: //www.patterndepot.com/put/8/Behavioral.html

The Iterator is one of the simplest and most frequently used of the design patterns. The Iterator pattern allows you to move through a list or collection of data using a standard interface without having to know the details of the internal representations of that data. In addition you can also define special iterators that perform some special processing and return only specified elements of the data collection.

Iterator 是最简单和最常用的设计模式之一。Iterator 模式允许您使用标准接口在数据列表或数据集合中移动,而无需了解该数据的内部表示的详细信息。此外,您还可以定义执行某些特殊处理并仅返回数据集合的指定元素的特殊迭代器。

回答by Gili

Iterators can be used against any sort of collection. They allow you to define an algorithm against a collection of items regardless of the underlying implementation. This means you can process a List, Set, String, File, Array, etc.

迭代器可用于任何类型的集合。它们允许您针对项目集合定义算法,而不管底层实现如何。这意味着您可以处理列表、集合、字符串、文件、数组等。

Ten years from now you can change your List implementation to a better implementation and the algorithm will still run seamlessly against it.

十年后,您可以将 List 实现更改为更好的实现,并且算法仍将针对它无缝运行。

回答by coobird

Using the Iteratorinterface allows any class that implements its methods to act as iterators. The notion of an interface in Java is to have, in a way, a contractual obligation to provide certain functionalities in a class that implementsthe interface, to act in a way that is required by the interface. Since the contractual obligations must be met in order to be a valid class, other classes which see the class implementsthe interface and thus reassured to know that the class will have those certain functionalities.

使用Iterator接口允许任何实现其方法的类充当迭代器。Java 中接口的概念在某种程度上具有契约义务,即在类中提供某些功能,implements接口以接口要求的方式运行。由于必须满足合同义务才能成为有效的类,因此其他类看到该类implements的接口并因此放心地知道该类将具有这些某些功能。

In this example, rather than implement the methods (hasNext(), next(), remove()) in the LinkedListclass itself, the LinkedListclass will declare that it implementsthe Iteratorinterface, so others know that the LinkedListcan be used as an iterator. In turn, the LinkedListclass will implement the methods from the Iteratorinterface (such as hasNext()), so it can function like an iterator.

在这个例子中,而不是hasNext(), next(), remove()LinkedList类本身中实现方法(),LinkedList类会声明它implementsIterator接口,所以其他人知道LinkedList可以用作迭代器。反过来,LinkedList该类将实现Iterator接口中的方法(例如hasNext()),因此它可以像迭代器一样运行。

In other words, implementing an interface is a object-oriented programming notion to let others know that a certain class has what it takes to be what it claims to be.

换句话说,实现一个接口是一种面向对象的编程概念,让其他人知道某个类具有它声称的样子。

This notion is enforced by having methods that must be implemented by a class that implements the interface. This makes sure that other classes that want to use the class that implements the Iteratorinterface that it will indeed have methods that Iterators should have, such as hasNext().

这个概念是通过具有必须由实现接口的类来实现的方法来强制执行的。这确保了其他想要使用实现Iterator接口的类的类确实具有迭代器应该具有的方法,例如hasNext().

Also, it should be noted that since Java does not have multiple inheritance, the use of interface can be used to emulate that feature. By implementing multiple interfaces, one can have a class that is a subclass to inherit some features, yet also "inherit" the features of another by implementing an interface. One example would be, if I wanted to have a subclass of the LinkedListclass called ReversibleLinkedListwhich could iterate in reverse order, I may create an interface called ReverseIteratorand enforce that it provide a previous()method. Since the LinkedListalready implements Iterator, the new reversible list would have implemented both the Iteratorand ReverseIteratorinterfaces.

另外,应该注意的是,由于 Java 没有多重继承,因此可以使用接口来模拟该功能。通过实现多个接口,一个类可以是一个子类来继承一些特性,但也可以通过实现一个接口来“继承”另一个类的特性。一个例子是,如果我想要一个LinkedList被调用类的子类,ReversibleLinkedList它可以以相反的顺序迭代,我可以创建一个被调用的接口ReverseIterator并强制它提供一个previous()方法。由于LinkedList已经实现了Iterator,新的可逆列表将同时实现IteratorReverseIterator接口。

You can read more about interfaces from What is an Interface?from The Java Tutorial from Sun.

您可以从什么是接口?来自 Sun 的 Java 教程。