
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 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);
Advertisements