Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java Iterator hold reference to elements of a linked list?

I need to have a list to hold several elements of an Enemy class in an app. This will function as an object pool to increase efficiency, as this particular class would otherwise be instantiated and killed off often.

I am so far probably going to use a linked list as it would be strongly beneficial to put inactive elements to the end of the list. My question is the following - in Java, does the Iterator provide direct access to the current element it is accessing by holding a reference to it (for linked lists), or does iterating to the next element require the Iterator to cycle from the beginning again (i.e. doesn't help efficiency, like a for loop which will always require going back to beginning for a linked list)?

From a C perspective, my question would be whether the Iterator contains a pointer to the current element it is accessing so that it doesn't have to loop from the beginning to gain access.

I have done some research on this, but I haven't been able to find an answer to it.

like image 743
Super Hacker Avatar asked Jul 30 '15 14:07

Super Hacker


1 Answers

It's not documented in the Javadoc, but you can check the implementation of LinkedList's listIterator and see that it does hold a reference to the current and next elements of the List :

public ListIterator<E> listIterator(int index) {
    return new ListItr(index);
}

private class ListItr implements ListIterator<E> {
    private Entry<E> lastReturned = header;
    private Entry<E> next;
    private int nextIndex;
    private int expectedModCount = modCount;
    ....

It only has to iterate over the LinkedList (from the start or from the end) when the ListIterator is created, since you can request the ListIterator to point to a specific index of the List when it's constructed.

like image 87
Eran Avatar answered Nov 14 '22 22:11

Eran