Return type of iterator() method in java

前端 未结 6 1502
耶瑟儿~
耶瑟儿~ 2021-01-03 07:46

I am a new-comer in Java and in process of learning. I need a an answer of following question supported with valid theory. Consider the following line-

Iterat         


        
6条回答
  •  [愿得一人]
    2021-01-03 08:46

    You are right saying that Iterator is an interface. So, some class must implement this interface so you can use it.

    The iterator interface defines what an iterator should do. In this case, the class ArrayList provides its own implementation of this interface.

    What you get from al.iterator() is the inner class of ArrayList Itr (see following code, which IS iterator. (as we kind of describe the IS-A relationship)

    (you can think of an inner class as a normal class for now. So the answer to your question is Itr, which is just a name, and all you should care about is its function, which is defined by interface Iterator.)

       /**
         * An optimized version of AbstractList.Itr
         */
        private class Itr implements Iterator {
            int cursor;       // index of next element to return
            int lastRet = -1; // index of last element returned; -1 if no such
            int expectedModCount = modCount;
    
            public boolean hasNext() {
                return cursor != size;
            }
           .....
      }
    

    This code is by Josh Bloch and Neal Gafter, who wrote the ArrayList class.

提交回复
热议问题