How to replace existing value of ArrayList element in Java

Kani picture Kani · Jun 1, 2014 · Viewed 292.3k times · Source

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.

Answer

Bill the Lizard picture Bill the Lizard · Jun 1, 2014

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

list.set( 2, "New" );