简体   繁体   中英

Linked List Iterator Java

I'm currently studying Linked List and on Iterators( using Lafore's ).

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.

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?

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. That would make insert operations inefficient.

And what use would be a Link.count field? 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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