Java Iterator Declaration

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.

+5
source share
5 answers

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 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).

+7
source

As a complement to other answers:

, Iterator , , . Collections, .

, . , List , someList.iterator (), , Iteraor Collections. , (, ..), , , zillion .

+1

Iterator, , Iterator. Iterator flavoursIter , , .

0

. Iterator interface , , . Iterator.

, , iterator(), Iterator. iterator() Iterator.

0

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

      }

}

, , , .

0

All Articles