Why does Java have a linked list if I can't get the next item without converting to an iterator?

Why does Java have a linked list if I can't access the next item without using an iterator?

+3


source to share


5 answers


You don't "convert a list to an Iterator", you "end up with an iterator over the list". You will find the iterator mechanism much easier to work with over time.



+4


source


LinkedList

is an implementation of an interface List

, which is also a relative value Collection

. A linked list is the concept itself, where each element of the list is contained in a node that knows the next element and the previous one. This is to maintain the order in which elements are inserted.

This does not happen with the other generic implementation: ArrayList

where each element is allocated in the underlying array, in which case the order is not guaranteed.



An iterator

is one of several ways to iterate over a list that has the great advantage of manipulating the list as it iterates (for example, the remove

iterator method does not end in ConcurrentModificationException

), and it is not related to the specific implementation of the collection traversed. This is not a collection, she just "manages" it in a friendly manner.

+4


source


Because you want your code not to be tied to a specific implementation. If it has the "next" function, and later you want to switch to an ArrayList implementation, you have a big problem ...

And more explanation: LinkedList

- this is another implementation for the interface List

. The main difference between ArrayList

and LinkedList

is that an array uses an expandable array to store a list when it LinkedList

contains a reference to the next object.

You still have a function get(index)

to get the object at the index, but it's inefficient (O (n)).

LinkedList is mainly used to shorten runtime when it is more efficient than ArrayList.

And further: LinkedList VS ArrayList

+1


source


An iterator is simply a method for traversing a list. The reason for having a data structure is LinkedList

related to the efficiency of some operations.

See this answer for a good description of how you can choose between LinkedList

and ArrayList

.

+1


source


If you just only want the next element, you can simply use

list.get(Int index+1);

      

And set the index to

index = list.indexOf(<The current object your are in>);

      

If you don't have any knowledge of which object you are on, you should use an iterator. It's pretty easy and very fast.

You can always use a for everyone.

for(List l : o)

      

+1


source







All Articles