• Post Reply Bookmark Topic Watch Topic
  • New Topic

Iterator  RSS feed

 
abalfazl hossein
Ranch Hand
Posts: 635
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


This is what java doc tells about Iterator:

Returns an iterator over the elements in this list (in proper sequence).

Iterator is just an interface,Does it return an interface?!!!


Interface has not a complete method,It has only a method without body.signature.Then How next method can work?
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The method will return an instance of a concrete class that implements Iterator. You don't need to know which particular class it is, all you need to know is that it implements that interface. Having the return type as an interface gives you that flexibility.

If you want to know exactly which class it is, though, try this:
 
Stephan van Hulst
Saloon Keeper
Posts: 7821
142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's polymorphism. iterator() will return *some* Iterator. This class will often be private, and the outside world won't know about it. We just know it is a concrete class that implements Iterator, so you can call the methods on it that Iterator declares.

[eta]

Too slow!
 
abalfazl hossein
Ranch Hand
Posts: 635
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It returns:


java.util.LinkedList$ListItr


I didn't see a class like this in JAVA doc.

It's polymorphism.


MAy you explain more how does it relates to polymorphism?
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As Stephan said, it can be a private class. In this case, LinkedList has a private inner class that implements Iterator, which is why you can't see it in the documentation (though you could download the source code if you really wanted to).

The point about polymorphism is that you don't need to know exactly which class it is. All you need to know is that it implements Iterator. Call the Iterator methods and polymorphism makes sure it all works correctly.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!