开发者

java creating an iterator for a custom data structure

开发者 https://www.devze.com 2023-03-05 19:37 出处:网络
So here\'s what I have: 1 interface called Set 1 abstract class which implements set 2 classes which extend the abstract class, called ArraySet and ListSet

So here's what I have:

  • 1 interface called Set
  • 1 abstract class which implements set
  • 2 classes which extend the abstract class, called ArraySet and ListSet

So in Set, I state Iterator <String> iterator(); and then in my 2 nonabstract classes, I have nested classes which are called ArrayIterator and ListIterator, which implement the iterator'开发者_Go百科s functionality. But the compiler complains that ArraySet and ListSet must implement Set.iterator(). How do I make it so that the compiler recognizes that ArrayIterator and ListIterator are the implementations of Set.iterator()?

So it looks like

interface Set extends Iterable< String > {  
...  
Iterator< String > iterator(); }  




class ArraySet extends AbstractClass {  
 ...  
    class ArrayIterator implements Iterator< String > { ... }  
 ...  
}  


You need to implement Set.iterator() in your non-abstract classes ArraySet and ListSet, ie:

In ArraySet:

Iterator<String> iterator() {
    // do something, probably return ArrayIterator ?
}

In ListSet:

Iterator<String> iterator() {
    // do something, probably return ListIterator ?
}

Also, I assume that both ArrayIterator and ListIterator implements Iterator


I know this is not a direct answer to your question. But just for the sake of knowledge you may want to know what is an internal iterator and what is an external iterator? Ref: Design Pattern book by GoF

or otherwise have a look at this

0

精彩评论

暂无评论...
验证码 换一张
取 消