beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java – Replace element in a LinkedList example

By Chaitanya Singh | Filed Under: Java Collections

In the last post we shared a tutorial on searching an element in LinkedList. Here we are gonna see how to replace an existing element value with the new value in LinkedList using the index of the element.

Example

The method we used in the below program is:
public E set(int index, E element): Replaces the element at the specified position in this list with the specified element.

Complete code:

import java.util.LinkedList;
public class ReplaceInLinkedList {
 
 public static void main(String[] args) {
 
    // Create a LinkedList
    LinkedList<String> linkedlist = new LinkedList<String>();
 
    // Add elements to LinkedList
    linkedlist.add("Cobol");
    linkedlist.add("JCL");
    linkedlist.add("C++");
    linkedlist.add("C#");
    linkedlist.add("Java");
 
    // Displaying Elements before replace
    System.out.println("Before Replace:");
    for(String str: linkedlist){
       System.out.println(str);
    }
 
    // Replacing 3rd Element with new value
    linkedlist.set(2, "NEW VALUE");
    System.out.println("\n3rd Element Replaced \n");

    // Displaying Elements after replace
    System.out.println("After Replace:");
    for(String str2: linkedlist){
       System.out.println(str2);
    }
 }
}

Output:

Before Replace:
Cobol
JCL
C++
C#
Java

3rd Element Replaced 

After Replace:
Cobol
JCL
NEW VALUE
C#
Java

Enjoyed this post? Try these related posts

  1. Java ArrayList remove(int index) Method example
  2. Vector in Java
  3. Java – Convert Vector to List example
  4. Java – Check if a particular element exists in LinkedList example
  5. Java – HashMap Iterator example
  6. How to convert an array to ArrayList in java

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

  • Java Tutorial
  • OOPs Concepts

Java Collections

  • ArrayList
  • LinkedList
  • ArrayList vs LinkedList
  • Vector
  • ArrayList vs Vector
  • HashMap
  • TreeMap
  • LinkedHashMap
  • HashSet
  • TreeSet
  • LinkedHashSet
  • Hashtable
  • HashMap vs Hashtable
  • Queue
  • PriorityQueue
  • Deque & ArrayDeque
  • Iterator
  • ListIterator
  • Comparable Interface
  • Comparator Interface
  • Java Collections Interview Q

MORE ...

  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap