简体   繁体   中英

How does the Java class ArrayList return an Iterator Object?

I know that you get it by calling the iterator() method on the ArrayList that you created, but what does that method look like?

Since Iterator is only an interface defined in Java, I am not sure how the ArrayList passes back a concrete implementation of the Iterator?

I know how to implement these myself for my own classes...I want to know how Java's ArrayList does it...maybe there is a concrete Iterator Class in the standard Library I don't know about?

You can find it out youself

System.out.println(new ArrayList().iterator().getClass());

I get class java.util.ArrayList$Itr probably you too. $ sign mean inner class (static or not). And if we go inside source we'll see

public Iterator<E> iterator() {
    return new Itr();
}

And later in this file

private class Itr implements Iterator<E> { ... }

The ArrayList class internally has an implementation of Iterator . Either that, or it has an internal method where it constructs an Iterator implementation from another class. The reason I don't know for sure is because the only way to know is to look through the source code, which I haven't done. The point of having an interface is that you don't need to know the internal implementation. You just know what the Iterator interface is capable of doing - which is defined by the interface spec.

And yes, somewhere there is a concrete implementation of the Iterator interface. The ArrayList class is using the constructor from such an implementation, creating the object, and returning it to you.

The iterator looks like this

Iterator<T> iterator() {
  return new Iterator<T>(this);
}

It return a new iterator every time.
Note you should do something like this in you code to not end up in an endless for loop

Iterator iterator = myCollections.iterator();

Use this iterator object to loop over you collection. If you do

while(myCollections.iterator().hasNext) {
   System.out.println(myCollections.iterator().next());
}

It will be an endless loop just printing the first object always.


EDIT:


To answer your question it comes from AbstractList which has an concrete implementation for it.

ArrayList has internally implemented the iterator as a nested class.

private class Itr implements Iterator<E> {
    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;
   }

and then it return object of it by the method iterator()

 public Iterator<E> iterator() {
    return new Itr();
 }

you can refer the sources code for better understanding ArrayList Source code

hope this ll help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM