In Java, a LinkedList is a data structure that represents a sequence of elements where each element is connected to its next and previous elements. It is part of the java.util package and provides methods to add, remove, and access elements in the list.
Here’s an example that demonstrates how to use a LinkedList:
import java.util.LinkedList;
public class LinkedListExample {
public static void main(String[] args) {
// Create a LinkedList of strings
LinkedList<String> names = new LinkedList<>();
// Add elements to the LinkedList
names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.add("David");
// Get the size of the LinkedList
int size = names.size();
System.out.println("Size of LinkedList: " + size);
// Access elements in the LinkedList
String firstElement = names.getFirst();
String lastElement = names.getLast();
System.out.println("First element: " + firstElement);
System.out.println("Last element: " + lastElement);
// Modify an element in the LinkedList
names.set(1, "Bobby");
System.out.println("Modified LinkedList: " + names);
// Remove an element from the LinkedList
names.remove(2);
System.out.println("LinkedList after removing an element: " + names);
// Check if an element is present in the LinkedList
boolean contains = names.contains("David");
System.out.println("LinkedList contains David: " + contains);
// Iterate over the elements in the LinkedList
for (String name : names) {
System.out.println("Name: " + name);
}
// Clear the LinkedList
names.clear();
System.out.println("LinkedList after clearing all elements: " + names);
}
}
In this example, we create a LinkedList of strings using the LinkedList class and add four elements to it using the add() method. We then use the size() method to get the size of the LinkedList and the getFirst() and getLast() methods to access the first and last elements.
We also demonstrate how to modify an element using the set() method, remove an element using the remove() method, check if an element is present in the LinkedList using the contains() method, and iterate over the elements using a for-each loop.
Finally, we use the clear() method to remove all elements from the LinkedList.
The output of this example might look something like this:
Size of LinkedList: 4 First element: Alice Last element: David Modified LinkedList: [Alice, Bobby, Charlie, David] LinkedList after removing an element: [Alice, Bobby, David] LinkedList contains David: true Name: Alice Name: Bobby Name: David LinkedList after clearing all elements: []
LinkedList provides several advantages over traditional arrays and ArrayList, including the ability to insert and remove elements at the beginning or middle of the list more efficiently. However, LinkedList can be less efficient than arrays and ArrayList when it comes to random access and memory usage.