Java.Collections.Why does LinkedList implement both List and Deque?

✅ Short Answer:

Because LinkedList is both:

  • A sequential list of elements (like an array),
  • AND a double-ended queue (deque).

So, Java designers made LinkedList implement both List and Deque interfaces to give us the best of both worlds.


📦 LinkedList in Java:

public class LinkedList<E> 
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, Serializable

✅ As a List:

  • You can:
    • Access elements by index: get(i), set(i)
    • Add/remove elements at any position: add(i, e), remove(i)
    • Iterate in order

This supports typical sequential data access.


✅ As a Deque:

  • You can:
    • Add/remove at both ends: addFirst, addLast, removeFirst, removeLast
    • Use it as a queue (FIFO): offer, poll
    • Or as a stack (LIFO): push, pop

This supports queue-like or stack-like behavior.

🎯 Why it makes sense:

  • LinkedList is built on a doubly linked list.
  • This structure naturally supports:
    • Fast insertion/removal at both ends and in the middle.
    • Efficient sequential iteration.
  • So it’s logical for it to implement both List and Deque.

⚠️ Caveat:

  • While LinkedList supports random access, it’s not efficient (O(n)) — unlike ArrayList (O(1)).

🧠 Tip:

Use LinkedList when:

  • You need frequent insertions/removals at the beginning or middle.
  • Or you’re implementing queues, stacks, or deques.

Avoid it if you need fast random access — go with ArrayList instead.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.