LinkedList does not provide index based access, so why does it have get(index) method?

It may not be efficient to retrieve items from a linked list by index, but linked lists do have indices, and sometimes you just need to retrieve an item at a certain index. When that happens, it's much better to have a get method than to force users to grab an iterator and iterate to the desired position. As long as you don't call it too much or the list is small, it's fine.


This is really just an implementation decision. While an array would probably be a fairly useless data structure if you can't look up elements by index, adding a by-index lookup to a linked-list implementation doesn't do any harm (well, unless users assume it's fast - see below), and it does come in handy sometimes.

One can assign every element a number as follows:

      0               1           2           3           4
Head (Element0) -> Element1 -> Element2 -> Element3 -> Element4 -> NULL

From here, it's trivial to write a function to return the element at some given index.

Note that a by-index lookup on a linked-list will be slow - if you're looking for let's say the element in the middle, you'll need to work through half the list to get there.


The previous answers imply that LinkedLists have indices.

However, a fixed index for every element in the data structure would defeat the purpose of the LinkedList and e.g. make some remove/add operations slower because the structure would need to be reindexed every time. This would take linear time, even for elements at the beginning and at the end of the list, that are crucial for Java's LinkedList's efficiency.

From Java's LinkedList implementation you can see that there is no constant time index access to the element, but rather a linear traversal where the exact element is figured out on the go.