Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java have a linked list if I cannot get the next element without converting to an iterator?

Why does Java have a linked list if I cannot get access to the next element without using an iterator?

like image 898
kisalaya Avatar asked Dec 20 '22 09:12

kisalaya


2 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.

like image 92
OldCurmudgeon Avatar answered Apr 05 '23 23:04

OldCurmudgeon


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.

like image 34
Fritz Avatar answered Apr 06 '23 00:04

Fritz