
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 in ArrayList Using ListIterator in Java
An element in ArrayList can be replaced using the ListIterator method set(). This method has a single parameter i.e. the element that is to be replaced and the set() method replaces it with the last element returned by the next() or previous() methods.
A program that demonstrates this is given as follows.
Example
import java.util.ArrayList; import java.util.ListIterator; public class Demo { public static void main(String[] args) { ArrayList<String> aList = new ArrayList<String>(); aList.add("Amanda"); aList.add("Taylor"); aList.add("Justin"); aList.add("Emma"); aList.add("Peter"); System.out.println("The ArrayList elements are: "); for (String s : aList) { System.out.println(s); } ListIterator<String> li = aList.listIterator(); li.next(); li.set("Monica"); System.out.println("\nThe ArrayList elements are: "); for (String s : aList) { System.out.println(s); } } }
Output
The output of the above program is as follows
The ArrayList elements are: Amanda Taylor Justin Emma Peter The ArrayList elements are: Monica Taylor Justin Emma Peter
Now let us understand the above program.
The ArrayList is created and ArrayList.add() is used to add the elements to the ArrayList. Then the ArrayList elements are displayed. A code snippet which demonstrates this is as follows
ArrayList<String> aList = new ArrayList<String>(); aList.add("Amanda"); aList.add("Taylor"); aList.add("Justin"); aList.add("Emma"); aList.add("Peter"); System.out.println("The ArrayList elements are: "); for (String s : aList) { System.out.println(s); }
The element “Amanda” is replaced by “Monica” using the ListIterator method set(). Then the ArrayList elements are again displayed. A code snippet which demonstrates this is as follows −
ListIterator<String> li = aList.listIterator(); li.next(); li.set("Monica"); System.out.println("\nThe ArrayList elements are: "); for (String s : aList) { System.out.println(s); }