Java Intermediate

0% completed

Previous
Next
Basic Overview of LinkedList Class

LinkedList is an implementation of the List and Deque interfaces in Java. It uses a doubly-linked list structure to store elements, which means each element (node) holds a reference to both its previous and next elements. This structure makes LinkedList particularly efficient for insertions and deletions at both ends, although random access (retrieving elements by index) is slower compared to an ArrayList.

Image

Unlike an ArrayList that uses a dynamic array, a LinkedList does not require contiguous memory. This makes it a flexible choice when your application involves frequent insertions or deletions from the middle of the list.

Syntax for Creating a LinkedList

LinkedList<Type> list = new LinkedList<Type>();
  • Explanation:
    This statement creates a new LinkedList that can store objects of the specified Type. Since LinkedList implements the List interface, it supports all standard list operations (e.g., add, get, set, remove) and additional methods for handling a double-ended queue.

Examples

Example 1: Basic Operations with LinkedList

In this example, we create a LinkedList of strings, add several elements, access elements by their index, and remove an element. This demonstrates the fundamental operations provided by the LinkedList class.

Java
Java

. . . .

Example Explanation:

  • Creation:
    • A LinkedList<String> called animals is created to store animal names.
  • Adding Elements:
    • The add() method is used to insert "Dog", "Cat", "Elephant", and "Giraffe" into the list.
  • Accessing Elements:
    • The get(0) method retrieves the first element ("Dog"), and get(2) retrieves the third element ("Elephant").
  • Removing an Element:
    • The remove("Cat") method deletes "Cat" from the list, demonstrating removal by value.
  • Outcome:
    • The final output shows the accessed elements and the state of the LinkedList after removal.

Example 2: Using LinkedList as a Deque

This example demonstrates how a LinkedList can function as a double-ended queue (Deque). We add elements at both ends and then remove elements from both ends, showcasing its versatility.

Java
Java

. . . .

Example Explanation:

  • Deque Functionality:
    • The LinkedList is used as a Deque to allow insertion and removal from both ends.
  • Adding Elements:
    • addFirst() and addLast() methods insert elements at the beginning and end, respectively.
  • Removing Elements:
    • removeFirst() removes the first element and removeLast() removes the last element.
  • Outcome:
    • The output shows the elements that were removed from each end, along with the current state of the deque.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next