How to replace existing value of ArrayList element in Java [duplicate]
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.
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");