- Collection Framework in JavaCollections Class in JavaList Interface in Java with ExamplesArrayList in JavaVector Class in JavaLinkedList in JavaQueue Interface In JavaPriorityQueue in JavaSet in JavaHashSet in JavaLinkedHashSet in JavaMap in the JavaHashMap in JavaHashtable in JavaLinkedHashMap in Java
LinkedList in Java
In Java, LinkedList
is an implementation of the List
interface that uses a doubly-linked list data structure to store elements. It provides methods for adding, removing, and accessing elements in the list, and can be used to implement stacks, queues, and other data structures.
Here's an example of how to use LinkedList
in Java
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");
// Access elements in the LinkedList
String firstPerson = names.getFirst(); // Alice
String lastPerson = names.getLast(); // Charlie
// Modify elements in the LinkedList
names.set(1, "Brian"); // [Alice, Brian, Charlie]
// Remove elements from the LinkedList
names.removeLast(); // [Alice, Brian]
// Iterate over the LinkedList using a for-each loop
for (String name : names) {
System.out.println(name);
}
// Clear the LinkedList
names.clear(); // []
}
}
In this example, we create a LinkedList
of strings called names
and add three elements to it using the add()
method. We then access elements in the LinkedList
using the getFirst()
and getLast()
methods, and modify elements in the LinkedList
using the set()
method. We also remove an element from the LinkedList
using the removeLast()
method. We then iterate over the LinkedList
using a for-each loop, and finally clear the LinkedList
using the clear()
method.
Note that LinkedList
provides several other methods, such as addFirst()
, addLast()
, isEmpty()
, size()
, and toArray()
, that can be used to manipulate and access elements in the LinkedList
. Additionally, LinkedList
can be used with any object type, including custom objects, by specifying the object type when creating the LinkedList
.
However, it's worth noting that LinkedList
has some performance drawbacks compared to other List
implementations, such as ArrayList
, due to its use of pointers and memory allocation. Therefore, it's generally recommended to use LinkedList
only when a linked list data structure is specifically required, such as for implementing certain algorithms or data structures. For most use cases, ArrayList
is usually a better choice due to its better performance characteristics.