I am still quite new to Java programming and I am trying to update an existing value of an ArrayList
by using this code:
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add( "Zero" );
list.add( "One" );
list.add( "Two" );
list.add( "Three" );
list.add( 2, "New" ); // add at 2nd index
System.out.println(list);
}
I want to print New
instead of Two
but I got [Zero, One, New, Two, Three]
as the result, and I still have Two
. I want to print [Zero, One, New, Three]
. How can I do this?
Thank You.
You can replace an element of an ArrayList using the set() method of the Collections class. This method accepts two parameters an integer parameter indicating the index of the element to be replaced and an element to replace with.
Replace element in arraylist while iterating Do not use iterator if you plan to modify the arraylist during iteration. Use standard for loop, and keep track of index position to check the current element. Then use this index to set the new element. Java program to search and replace an element in an ArrayList.
replaceAll(e -> e * 2); Here, e -> e * 2 - multiply each element of the arraylist by 2. replaceAll() - replaces all elements of the arraylist with results of e -> e * 2.
Use the set
method to replace the old value with a new one.
list.set( 2, "New" );
If you are unaware of the position to replace, use list iterator to find and replace element ListIterator.set(E e)
ListIterator<String> iterator = list.listIterator();
while (iterator.hasNext()) {
String next = iterator.next();
if (next.equals("Two")) {
//Replace element
iterator.set("New");
}
}
Use ArrayList.set
list.set(2, "New");
You must use
list.remove(indexYouWantToReplace);
first.
Your elements will become like this. [zero, one, three]
then add this
list.add(indexYouWantedToReplace, newElement)
Your elements will become like this. [zero, one, new, three]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With