A linked list is a fundamental data structure in programming. It can store data and a references to the next and/or to the previous node. There can be a singly linked list, a doubly linked list and a circularly linked list.
The code below show you how to use the java.util.LinkedList
class to create a linked list. In the example we create a LinkedList
to store a string object using the add(Object o)
method. After create the list we iterate the list and print out the contents.
package org.kodejava.util;
import java.util.List;
import java.util.LinkedList;
public class LinkedListCreate {
public static void main(String[] args) {
// Creates a new instance of java.util.LinkedList and
// adds five string object into the list.
List<String> grades = new LinkedList<>();
grades.add("A");
grades.add("B");
grades.add("C");
grades.add("E");
grades.add("F");
// Iterates the LinkedList object using the for each
// statement.
for (String grade : grades) {
System.out.println("Grade: " + grade);
}
}
}
This program will produce the following output:
Grade: A
Grade: B
Grade: C
Grade: E
Grade: F
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024