Linked List In Java
LinkedList in Java
The LinkedList class in Java is an implementation of the List interface that provides a doubly-linked list data structure. It offers a flexible way to store and manipulate a collection of elements. Unlike an ArrayList, a LinkedList does not use contiguous memory allocation but rather connects elements through references.
Declaration and Initialization
To use a LinkedList in Java, you need to import the java.util.LinkedList
package. Here's an example of declaring and initializing a LinkedList:
import java.util.LinkedList;
public class Example {
public static void main(String[] args) {
LinkedList<String> animals = new LinkedList<>();
// Adding elements to the LinkedList
animals.add("Dog");
animals.add("Cat");
animals.add("Elephant");
// Accessing elements
System.out.println("Access Element = "+animals.get(0)); // Output: Dog
// Modifying elements
animals.set(1, "Lion");
// Removing elements
animals.remove(2);
// Iterating over elements
for (String animal : animals) {
System.out.println("Iterating Elements = "+animal);
}
}
}
Common LinkedList Operations
Here are some commonly used operations with Linked List:
add(element)
: Adds an element to the end of the LinkedList.get(index)
: Retrieves the element at the specified index.set(index, element)
: Replaces the element at the specified index with a new element.remove(index)
: Removes the element at the specified index.size()
: Returns the number of elements in the LinkedList.isEmpty()
: Checks if the LinkedList is empty.clear()
: Removes all elements from the LinkedList.
These are just a few examples of what you can do with Linked List in Java. They offer many more methods and are especially useful when frequent insertions and deletions are required. Linked List provide a flexible and efficient way to manage collections of elements.