Implement Java Iterator and Iterable in same class?

后端 未结 4 1677
终归单人心
终归单人心 2020-12-13 21:03

I am trying to understand Java Iterator and Iterable interfaces

I am writing this class

class MyClass implements Iterable&         


        
4条回答
  •  再見小時候
    2020-12-13 21:16

    You should almost never implement both Iterable and Iterator in the same class. They do different things. An iterator is naturally stateful - as you iterate using it, it has to update its view of the world. An iterable, however, only needs to be able to create new iterators. In particular, you could have several iterators working over the same original iterable at the same time.

    Your current approach is pretty much okay - there are aspects of the implementation I'd change, but it's fine in terms of the separation of responsibilities.

提交回复
热议问题