Why does Java have a linked list if I cannot get access to the next element without using an iterator?
Why does Java have a linked list if I cannot get the next element without converting to an iterator?
-
1Can you share your way to convert list to iterator? o.O – gkuzmin Feb 14 '13 at 13:25
5 Answers
You don't "convert the list to an Iterator" you "get an iterator over the list". You will find the iterator mechanism much easier to work with in time.

- 64,482
- 16
- 119
- 213
LinkedList
is an implementation of the List
interface that is also a relative of Collection
. A linked list is a concept itself, where every element of the list is contained in a node that knows the next element and the previous one. This is done in order to maintain the insertion order of the elements.
This doesn't happen with another common implementation: ArrayList
where each element is allocated in the underlying array and, in this case, order is not guaranteed.
An iterator
is one of the multiple ways to iterate through a list that happens to have the great adventage of managing the list while iterating it (for example, the remove
method of an iterator doesn't end up in a ConcurrentModificationException
) and it's not related to the particular implementation of the traversed collection. It is not the collection, it just "manages" it in a loop-friendly way.

- 9,987
- 4
- 30
- 49
Because you want to keep your code not related to a specific implementation. If it'll have "next" function, and later on you'd want to change to ArrayList implementation, you'll have a big problem...
And more explanation:
LinkedList
is just another implementation for List
interface.
The main difference between ArrayList
and LinkedList
is that array uses extendable array to hold the list, when LinkedList
holds a reference to the next object.
You still have get(index)
function to get object in index, but its not efficient (O(n)).
The LinkedList used mostly in order to reduce running time when it is more efficient that ArrayList.
And further more: LinkedList VS ArrayList

- 1
- 1

- 18,858
- 6
- 40
- 61
The iterator is simply a method of traversing the list. The reason to have a LinkedList
data structure is related to the efficiency of certain operations.
See this answer for a good description of how one might choose between a LinkedList
and an ArrayList
.

- 1
- 1

- 67,400
- 29
- 193
- 254
If you simply would like to only have the next element, you could just use
list.get(Int index+1);
And have index set to
index = list.indexOf(<The current object your are in>);
If you don't have the knowledge of what object you are in at the moment, you have to use iterator. Which is fairly easy and very fast.
One can always use a for each.
for(List l : o)

- 1,366
- 3
- 21
- 42