How to replace existing value of ArrayList element in Java

JavaArraylist

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

Use the set method to replace the old value with a new one.

list.set( 2, "New" );

Solution 2 - Java

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");
     }
 }

Solution 3 - Java

Use ArrayList.set

list.set(2, "New");

Solution 4 - Java

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]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKaniView Question on Stackoverflow
Solution 1 - JavaBill the LizardView Answer on Stackoverflow
Solution 2 - JavaSivabalanView Answer on Stackoverflow
Solution 3 - JavawonceView Answer on Stackoverflow
Solution 4 - JavaThwin Htoo AungView Answer on Stackoverflow