Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace existing value of ArrayList element in Java [duplicate]

Tags:

java

arraylist

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.

like image 924
Kani Avatar asked Jun 01 '14 14:06

Kani


People also ask

How do you replace values in an ArrayList?

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.

How do you modify an ArrayList while iterating?

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.

How do you replace all elements in an ArrayList in Java?

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.


4 Answers

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

list.set( 2, "New" );
like image 118
Bill the Lizard Avatar answered Oct 05 '22 16:10

Bill the Lizard


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");
     }
 }
like image 45
Sivabalan Avatar answered Oct 05 '22 14:10

Sivabalan


Use ArrayList.set

list.set(2, "New");
like image 28
wonce Avatar answered Oct 05 '22 14:10

wonce


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]

like image 25
Thwin Htoo Aung Avatar answered Oct 05 '22 15:10

Thwin Htoo Aung