To add an item before the first item in the linked list we use the LinkedList.addFisrt()
method and to add an items after the last item in the linked list we use the LinkedList.addLast()
method.
package org.kodejava.util;
import java.util.LinkedList;
public class LinkedListAddItems {
public static void main(String[] args) {
LinkedList<String> grades = new LinkedList<>();
grades.add("B");
grades.add("C");
grades.add("D");
grades.add("E");
System.out.println("Original values are:");
System.out.println("====================");
for (String grade : grades) {
System.out.println("Grade = " + grade);
}
grades.addFirst("A");
grades.addLast("F");
System.out.println("New values are:");
System.out.println("====================");
for (String grade : grades) {
System.out.println("Grade = " + grade);
}
}
}
The result of the program are the following:
Original values are:
====================
Grade = B
Grade = C
Grade = D
Grade = E
New values are:
====================
Grade = A
Grade = B
Grade = C
Grade = D
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