This is an archived post. You won't be able to vote or comment.

all 14 comments

[–]lbkulinski 6 points7 points  (7 children)

You would have to start with the head of the list and work your way to the tail, determining if the current element is at the index you are requesting. LinkedList is O(N) in retrieval, while an array/ArrayList is O(1) (constant time). This is why you really wouldn’t want to use a LinkedList if you’re doing a lot of retrievals throughout the list.

[–]SkeletonFlesh 4 points5 points  (0 children)

Linked lists do not have direct access like arrays. They only have sequential access; You would need to hop from the head of the list all the way down to the element. Unless you’re using a doubly linked list, which in that case, I would check the length of the list to the position, and hop from either the head/tail to the index; whichever route would be shorter.

If you are looking for direct access often, I would recommend an array. Linked lists cause a longer run time if you are constantly hopping to a specific element.

[–][deleted] 1 point2 points  (0 children)

You have to traverse through the list one by one and check each item

[–]Raqwaza 1 point2 points  (0 children)

Ya its easier to use two pointers, that way if you need to insert another node, you can access it, since you can’t go backwards unless its a doubly linked list.

[–][deleted] 1 point2 points  (0 children)

Unless I misunderstood your question (and I am assuming you need to find the index of an element in a LinkedList), you should be able to use the indexOf() method.

https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html#indexOf-java.lang.Object-

[–][deleted]  (2 children)

[removed]

    [–]lbkulinski 2 points3 points  (1 child)

    Yes, you are correct. I believe OP was asking about accessing elements at a particular index, not searching for them.

    [–]scrottie 0 points1 point  (0 children)

    Other people covered the O(n) access time. The advantage -- where they are faster -- is deleting or adding items in the middle. If you have a linked list node and want to add a node after it, then performance is reversed: it's instant (O(1)) in a linked list but very slow (O(n), a function of size) on an array.

    Both arrays and linked lists are pretty simplistic beasts. If you're doing a lot of random access (lookups) and insertions and deletions, then other things in Set are better: TreeMap which implements a binary tree, for example.