161

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?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Kani
  • 1,735
  • 2
  • 11
  • 12

4 Answers4

314

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

list.set( 2, "New" );
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
33

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");
     }
 }
Sivabalan
  • 2,908
  • 2
  • 24
  • 21
26

Use ArrayList.set

list.set(2, "New");
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
wonce
  • 1,893
  • 12
  • 18
  • 1
    What if I don't know the Index of Object, Still I want to replace the object with new in specific place. Is it possible? – santhanam May 29 '17 at 06:57
  • 7
    @santhanam You can use list.set(list.indexOf(oldObject), newObject); – Alberto Alegria Jun 03 '17 at 01:07
  • 1
    @Alberto what if it was the same element but updated ? – Mohammad Ali Mar 15 '18 at 12:39
  • @MohammadAli override `equals` method of your object class and implement your own rules to check if objects are the same (equal), after that `List.contains(object)`, `List.indexOf(object)`, `object1.equals(object2)` will work ok – user25 Jan 26 '19 at 14:41
  • @santhanam Beware that indexOf will return the index of the first occurance of the element – arxakoulini Sep 16 '20 at 10:55
4

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]

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
  • 2
    this approach only works if you are not iterating through the list at the time of the _remove_ method call. See [link](http://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re) for more information – wegenmic Jul 27 '16 at 08:29