I am very confused about the iterator in Java.
The textbook said the following:
In the Java programming language, an interface is a reference type, similar to a class that can contain only constants, method signatures, and nested types. There are no organs for methods. Interfaces cannot be instantiated - they can only be implemented by classes or extended by other interfaces. Extension is discussed later in this lesson.
Then I saw another tutorial with this:
Iterator<String> flavoursIter = aFlavours.iterator();
I understand that aFlavours inherits the functions of an iterator that returns an iterator interface. I just donβt understand what is really happening on this line. I thought you could not create an instance?
Perhaps I do not make sense, but please tell me that we are leaving the track.
Saying that it cannot be created, they mean that you cannot do it Iterator i = new Iterator();. Since Iterator is an interface, it itself does not have an implementation. When you do
Iterator i = new Iterator();
Iterator flavoursIter = aFlavours.iterator();
what you are doing is calling a method called an "iterator" in an object aFlavoursthat returns an instance of some class that implements the Iterator interface (you really donβt know which class it is and does not have to guarantee everything that you that it supports all methods defined in the Iterator interface).
aFlavours
As a complement to other answers:
, Iterator , , . Collections, .
Iterator
, . , List , someList.iterator (), , Iteraor Collections. , (, ..), , , zillion .
List
someList.iterator ()
Iteraor
Iterator, , Iterator. Iterator flavoursIter , , .
Iterator flavoursIter
. Iterator interface , , . Iterator.
interface
, , iterator(), Iterator. iterator() Iterator.
iterator()
Kick, iterator(), Iterator.for
public Iterator iterator() { return new ArryListIterator implments Iterator { public T next() { // code for next() } public boolean hasNext() {//code for hashNext()} //others codes }
}
, , , .