To insert an item at any position into a linked list object we can use the add(int index, Object o)
method. This method takes the index
to where the new object to be inserted and the object to be inserted itself.
package org.kodejava.util;
import java.util.LinkedList;
public class LinkedListAddDemo {
public static void main(String[] args) {
LinkedList<String> names = new LinkedList<>();
names.add("Alice");
names.add("Bob");
names.add("Mallory");
System.out.println("Original values are:");
System.out.println("====================");
for (String name : names) {
System.out.println("Name = " + name);
}
// Add a new item to the list at index number 2. Because
// a list are 0 based index Carol will be inserted after
// Bob.
names.add(2, "Carol");
System.out.println("New values are:");
System.out.println("====================");
for (String name : names) {
System.out.println("Name = " + name);
}
}
}
The result of our program are:
Original values are:
====================
Name = Alice
Name = Bob
Name = Mallory
New values are:
====================
Name = Alice
Name = Bob
Name = Carol
Name = Mallory
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