4

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

kisalaya
  • 101
  • 3

5 Answers5

4

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.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
4

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.

Fritz
  • 9,987
  • 4
  • 30
  • 49
1

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

Community
  • 1
  • 1
BobTheBuilder
  • 18,858
  • 6
  • 40
  • 61
1

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.

Community
  • 1
  • 1
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
1

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)
petur
  • 1,366
  • 3
  • 21
  • 42