简体   繁体   English

链表迭代器Java

[英]Linked List Iterator Java

I'm currently studying Linked List and on Iterators( using Lafore's ). 我目前正在研究链表和迭代器( 使用Lafore的 )。

I am not sure as to why we need Iterators in the first place. 我不确定为什么首先需要迭代器。

Say your class Link looks like below. 说您的课程链接如下所示。

class Link{
public int iData; // data
public double dData; /d/ data
public Link next; //reference to next link
//----------------------------------
public Link(int id, double dd){
    iData = id; //initialize data
    dData = dd;// 'next' is automatically set to null.
}
//----------------------------------
public void displayLink(){
    System.out.print("{"+iData+", "+dData+"} ");
}
//----------------------------------
}//end class Link

And your LinkList class has a field Link first and some operations for the list. 并且您的LinkList类具有一个“ 首先链接”字段和该列表的一些操作。

My question is 我的问题是

Why can't I just add an int variable(ex: int count; ) as a field for the Link class and then just increment it whenever it's called instead of building a whole class ,called Iterators, just to traverse back and forth in the list? 为什么我不能仅将一个int变量(例如: int count; )添加为Link类的字段,然后在每次调用它时都将其递增,而不是构建一个称为Iterators的整个类,而只是在该类中来回遍历清单?

The book says 这本书说

One problem with this approach is that you might need more than one such reference, just as you often use several array indices at the same time. 这种方法的一个问题是,您可能需要多个这样的引用,就像您经常同时使用多个数组索引一样。

What does it mean? 这是什么意思? Can you give me an example of when this problem occurs? 您能举个例子说明这个问题何时发生吗?

Thank you in advance. 先感谢您。

If you add a count field in Link , then if you insert an element somewhere in the middle, you would have to update the .count field in all subsequent elements. 如果在Link添加一个count字段,则如果在中间的某个位置插入一个元素,则必须在所有后续元素中更新.count字段。 That would make insert operations inefficient. 那将使插入操作效率低下。

And what use would be a Link.count field? Link.count字段有什么用? I don't see a generally useful purpose for that. 我没有看到通常有用的目的。

An iterator is nice, but you don't actually need one. 迭代器很不错,但是实际上不需要一个迭代器。 If you want to traverse a linked list, you can certainly do without it. 如果要遍历链接列表,则可以不用它。 So I really don't see your objection against iterators on linked lists. 因此,我真的没有看到您反对链表上的迭代器。

Iterators are useful as they encapsulate the concept of iterating. 迭代器非常有用,因为它们封装了迭代的概念。 The single responsibility of an iterator is that it iterates over some iterable. 迭代器的唯一职责是对一些可迭代的对象进行迭代。 You can iterate over the elements without having to know anything about the underlying storage. 您可以遍历元素,而无需了解有关基础存储的任何知识。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM