I am new to Java.
Java has Collection interface
public interface Collection<E> extends Iterable<E>
{ // a lot of other stuff.
Iterator<E> iterator(); }
What I don’t understand is how does Iterator Interface is tying into Collection Interface ? When I look at the Collection Interface, I see that it has a method that returns Iterator. When Iterator for Collection is created, where does JVM looks to create an object that IS-An Iterator ?
Thanks !
Ok so this is all pretty advanced java stuff and it will be pretty tough to explain in one go here but I will do my best.
BACKGROUND: If you don’t know about those funny
<E>things, you should do a bit of looking into Java Generics. Also, if you don’t already, you really need to know what an interface is. One really basic way to think of it is as a promised bit of functionality a class promises to provide.Now to answer your question: There are three interfaces in the above code snippet, and if you want to create your own collection class you will need to provide implementations of all three:
The first is
Collection. This is a simple concept that maps to the real world, it is literally a “collection” of objects. I think you get this…The next one is
Iterablethis defines a singe type of behavior that all collections need to provide: the ability to traverse all of the elements of a collection, while accessing them one by one ie “iterate” over them. But it doesn’t stop there. As you pointed out theIterablefunctionality is provided by objects that implement the last interface:Iterator: objects that implement this interface, actually know how to traverse the elements of a collection class, they hide all the details of how its actually done from thier clients and proved a few clean easy methods for actually doing it likehasNext()which checks to see if there are more things in the collection to visit andnext()which actually visits the next thing.phew…