How to update a linked list in Java



Problem Description

How to update a linked list?

Solution

Following example demonstrates how to update a linked list by using listname.add() and listname.set() methods of LinkedList class.

import java.util.LinkedList;

public class MainClass {
   public static void main(String[] a) {
      LinkedList<String> officers = new LinkedList<String>();
      officers.add("B");
      officers.add("B");
      officers.add("T");
      officers.add("H");
      officers.add("P");
      System.out.println(officers);
      officers.set(2, "M");
      System.out.println(officers);
   }
}

Result

The above code sample will produce the following result.

[B, B, T, H, P]
[B, B, M, H, P]

The following is an example to update a linked list by using listname.add() and listname.set() methods of LinkedList class

import java.util.LinkedList;
 
public class Demo {
   public static void main(String[] args) {
      LinkedList llist = new LinkedList();
      llist.add("1");
      llist.add("2");
      llist.add("3");
      llist.add("4");
      llist.add("5");
      System.out.println("Original LinkedList contains : " + llist);
      llist.set(3, "6");
      System.out.println("Updated LinkedList contains : " + llist);
   }
}

The above code sample will produce the following result.

Original LinkedList contains : [1, 2, 3, 4, 5]
Updated LinkedList contains : [1, 2, 3, 6, 5]
java_data_structure.htm
Advertisements