Curriculum
In Java, LinkedList
is a class that implements the List
interface and provides a way to store a collection of elements as a linked list. In this answer, I will explain how to use LinkedList
in Java, as well as some of its commonly used methods.
To use LinkedList
in Java, you must first import the java.util.LinkedList
class. You can create a new LinkedList
by instantiating the class with a type parameter that specifies the type of elements the list will hold. Here’s an example of how to create a new LinkedList
that can hold elements of type String
:
LinkedList<String> list = new LinkedList<>();
Once a LinkedList
has been created, elements can be added or removed from it using the following methods:
// Add an element to the end of the list list.add("apple"); // Add an element at the specified index list.add(1, "banana"); // Remove an element at the specified index String removed = list.remove(0); // Remove the first occurrence of an element boolean success = list.remove("banana"); // Remove and return the first element in the list String first = list.removeFirst(); // Remove and return the last element in the list String last = list.removeLast(); // Return the first element in the list without removing it first = list.peekFirst(); // Return the last element in the list without removing it last = list.peekLast(); // Remove all elements from the list list.clear();
LinkedList
provides several methods to access elements in the list:
// Get the number of elements in the list int size = list.size(); // Check if the list is empty boolean isEmpty = list.isEmpty(); // Get the element at the specified index String element = list.get(1); // Set the element at the specified index list.set(1, "cherry"); // Convert the list to an array String[] array = list.toArray(new String[0]); // Iterate over the elements in the list using a for-each loop for (String element : list) { System.out.println(element); }
Some other commonly used methods provided by the LinkedList
class include:
// Add an element to the front of the list list.addFirst("date"); // Add an element to the end of the list list.addLast("elderberry"); // Get the first element in the list first = list.getFirst(); // Get the last element in the list last = list.getLast(); // Remove and return the first element in the list, returns null if the list is empty first = list.poll(); // Remove and return the first element in the list, throws an exception if the list is empty first = list.remove();
One important thing to keep in mind when using a LinkedList
is that it provides a way to store elements as a linked list, which can be useful for certain types of algorithms. However, because it uses a linked list, it can be slower than other types of collections for random access to elements, such as when using the get()
method. It’s important to understand the behavior of the methods you are using and how they may affect the performance of your code.