LinkedList
The LinkedList class in Java is a doubly linked list implementation of the List interface. It provides various methods that allow you to add, remove, and access elements in the LinkedList.
To use the LinkedList class, you need to import the java.util.LinkedList package.
Here's an example that demonstrates the usage of the LinkedList class:
TEXT/X-JAVA
1class Main {
2
3 public static void main(String[] args) {
4 // Create a LinkedList
5 LinkedList<String> linkedList = new LinkedList<>();
6
7 // Add elements to the LinkedList
8 linkedList.add("Element 1");
9 linkedList.add("Element 2");
10 linkedList.add("Element 3");
11
12 // Access elements in the LinkedList
13 String element = linkedList.get(1);
14 System.out.println("Element at index 1: " + element);
15
16 // Update an element
17 linkedList.set(0, "Updated Element");
18
19 // Remove an element
20 linkedList.remove(2);
21
22 // Check if an element exists
23 boolean exists = linkedList.contains("Element 2");
24 System.out.println("Element 2 exists: " + exists);
25
26 // Get the size of the LinkedList
27 int size = linkedList.size();
28 System.out.println("Size of the LinkedList: " + size);
29 }
30
31}xxxxxxxxxx31
}class Main { public static void main(String[] args) { // Create a LinkedList LinkedList<String> linkedList = new LinkedList<>(); // Add elements to the LinkedList linkedList.add("Element 1"); linkedList.add("Element 2"); linkedList.add("Element 3"); // Access elements in the LinkedList String element = linkedList.get(1); System.out.println("Element at index 1: " + element); // Update an element linkedList.set(0, "Updated Element"); // Remove an element linkedList.remove(2); // Check if an element exists boolean exists = linkedList.contains("Element 2"); System.out.println("Element 2 exists: " + exists); // Get the size of the LinkedList int size = linkedList.size(); System.out.println("Size of the LinkedList: " + size); }OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment


