• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why iterator should be inner class in collections?  RSS feed

 
BadriNath Ojha
Greenhorn
Posts: 12
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Iteratior provides the functionality of traversing and removal which we can achieve through normal for loop and remove() of the data structure.
Then, why do we need Iterator explicitly and as an inner class?
Thanks in advance.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What exactly do you mean?

It is not necessary that an Iterator is defined as an inner class.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
BadriNath Ojha wrote:Then, why do we need Iterator explicitly and as an inner class?

As Jesper says, you don't. It is, however, common practise to make them nested classes (either inner or static), since they will generally only be applicable to a particular type of collection. Making them inner (non-static) simply saves you having to pass the collection instance to the Iterator.

HIH

Winston
 
Campbell Ritchie
Marshal
Posts: 56584
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need an Iterator specifically because most of the interfaces in the Collections Framework have an iterator method.
It is simply convenient to implement the Iterator as an inner class, so it is available and each implementation can find its own Iterator. It could just as easily have been implemented as a package‑private class in the java.util package.
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:It is simply convenient


It could just as easily


 
Paweł Baczyński
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One reason could be that inner class have access to outer class' private members.
So internal data of collection can be private instead of package-private.
 
BadriNath Ojha
Greenhorn
Posts: 12
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to all you guys. Your answers were really helpful.
 
Paweł Baczyński
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pawel Pawlowicz wrote:One reason could be that inner classes have access to outer class' private members.
So internal data of collection can be private instead of package-private.

Nah, I wanted to edit, not quote myself :P
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!