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 build simple search page using ZK and Spring Boot? - March 8, 2023
- How do I calculate days between two dates excluding weekends and holidays? - January 12, 2023
- How do I discover the quarter of a given date? - January 11, 2023