I am very new to Java collection framework,pardon me if this question sounds silly.
there is one method 'iterator()' specified in 'Iterable ' Interface which returns an 'Iterator ' over elements of type E now AbstractList (abstract class) provided an implementation to this method and returns an 'Iterator' so my question is how can it can return an 'Iterator' without implementing interface 'Iterator'?
References :
ArrayList : https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/ArrayList.html#iterator()
AbstractList: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/AbstractList.html#iterator()
Iterable: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Iterable.html#iterator()
Iterator: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Iterator.html
My understanding:
as we know functional interfaces can be implemented without using 'implements' keyword i.e by the means of anonymous class and lambda Expression but the 'Iterator' Interface is not a functional interface so a class needs to implement it using a 'implements' keyword but here the 'AbstractList' class(abstract) implements it without using the 'implements' keyword?
Note that i am talking about 'Iterator' interface not 'Iterable' Interface ,in Interface 'Iterable ' there is one method 'iterator()' whose declaration looks like following- " Iterator iterator() " and this method is implemented by AbstractList class, since it provided implementation to 'iterator()' method which means that it must have implemented Interface 'Iterator' because return type of method is 'Iterator' but AbstractList class doesnot 'implements' Interface Iterator ?
Well, that is not very Collections specific. Any class can, of course, provide an implementation for X without having the class itself implementing that interface:
(Example could be shortened using Lambdas, and
A.thisalso is not explicitly required, but to increase understandibility).AbstractListdoes more or less the same: Itsiterator()method returns anIteratorimplementation using methods of the AbstractList to implement the methods from theIteratorinterface.More Collections-specific information:
AbstractListmust not implement theIteratorinterface, as anIteratoris a stateful object which can be used to iterate over an arbitrary list of elements - once. As soon as it is at the end (i.e.,hasNext()returnsfalse), it cannot be used again. So, anyListdirectly implementing theIteratorinterface could only be iterated once.That's why each call to
iterator()on anAbstractListreturns a new object - with a new state for iterating the list from the beginning to the end.