- Java Programming Examples
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Tutorial
- Java - Tutorial
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
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