- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Replace an element of a Java LinkedList
An element in an Java LinkedList can be replaced using the java.util.ArrayList.set() method. This method has two parameters i.e the index at which the LinkedList element is to be replaced and the element that it should be replaced with. ArrayList.set() method returns the element that was at the position specified at the index previously.
A program that demonstrates this is given as follows −
Example
import java.util.LinkedList; public class Demo { public static void main(String[] args) { LinkedList<String> l = new LinkedList<String>(); l.add("Pear"); l.add("Apple"); l.add("Mango"); l.add("Guava"); l.add("Orange"); System.out.println("The LinkedList is: " + l); l.set(2, "Peach"); System.out.println("The LinkedList is: " + l); } }
Output
The LinkedList is: [Pear, Apple, Mango, Guava, Orange] The LinkedList is: [Pear, Apple, Peach, Guava, Orange]
Now let us understand the above program.
The LinkedList l is created. Then LinkedList.add() is used to add the elements to the LinkedList. Then LinkedList.set() is used to replace the element “Mango” with “Peach” at index 2. Then the LinkedList is displayed. A code snippet which demonstrates this is as follows −
LinkedList<String> l = new LinkedList<String>(); l.add("Pear"); l.add("Apple"); l.add("Mango"); l.add("Guava"); l.add("Orange"); System.out.println("The LinkedList is: " + l); l.set(2, "Peach"); System.out.println("The LinkedList is: " + l);
- Related Articles
- How to replace an element of an ArrayList in Java?
- Replace an element from a Java List using ListIterator
- Replace an element at a specified index of the Vector in Java
- Search a particular element in a LinkedList in Java
- Add a single element to a LinkedList in Java
- Remove a specific element from a LinkedList in Java
- How to remove an element from ArrayList or, LinkedList in Java?
- How do you find the element of a LinkedList in Java?
- Retrieve the last element from a LinkedList in Java
- Replace an element in an ArrayList using the ListIterator in Java
- Delete first and last element from a LinkedList in Java
- Java Program to Get the middle element of LinkedList in a single iteration
- Iterate through a LinkedList using an Iterator in Java
- Convert LinkedList to an array in Java
- Create an object array from elements of LinkedList in Java

Advertisements