Wednesday, January 17, 2024

How to replace an element of ArrayList in Java? Example

You can use the set() method of java.util.ArrayList class to replace an existing element of ArrayList in Java. The set(int index, E element) method takes two parameters, the first is the index of an element you want to replace, and the second is the new value you want to insert. You can use this method as long as your ArrayList is not immutable, I mean,  not created using the Collections.unmodifiableList(), in such case the set() method throws java.lang.UnsupportedOperationExcepiton

Though you can also use the set() method with the List returned by Arrays.asList() method as oppose to add() and remove() which is not supported there. You just need to be careful with the index of elements. For example, if you want to replace the first element then you need to call set(0, newValue) because similar to an array, the ArrayList index is also zero-based.

Now, the questions come why do you want to replace an element in the ArrayList? Why not just remove the element and insert a new one? Well, obviously the remove and insert will take more time than replace. 

The java.util.ArrayList provides O(1) time performance for replacement, similar to size(), isEmpty(), get()iterator(), and listIterator() operations which runs in constant time.

Now, you may wonder that why set() gives O(1) performance but add() gives O(n) performance, because it could trigger resizing of the array, which involves creating a new array and copying elements from the old array to the new array.  You can also see these free Java courses to learn more about the implementation and working of ArrayList in Java.




Replacing an existing object in ArrayList

Here is an example of replacing an existing value from ArrayList in Java. In this example, I have an ArrayList of String which contains names of some of the most popular and useful books for Java programmers. 

Our example replaces the 2nd element of the ArrayList by calling the ArrayList.set(1, "Introduction to Algorithms") because the index of the array starts from zero. You should read a comprehensive course like The Complete Java Masterclass on Udemy to learn more about useful collection classes in Java, including ArrayList.

How to replace an element of ArrayList in Java? Example



Java Program to replace elements in ArrayList

import java.util.ArrayList;
import java.util.List;

/*
 * Java Program to demonstrate how to replace existing value in 
 * ArrayList.
 */

public class ArrayListSetDemo {

  public static void main(String[] args) {

    // let's create a list first
    List<String> top5Books = new ArrayList<String>();
    top5Books.add("Clean Code");
    top5Books.add("Clean Coder");
    top5Books.add("Effective Java");
    top5Books.add("Head First Java");
    top5Books.add("Head First Design patterns");

    // now, suppose you want to replace "Clean Coder" with
    // "Introduction to Algorithms"
    System.out.println("ArrayList before replace: " + top5Books);

    top5Books.set(1, "Introductoin to Algorithms");

    System.out.println("ArrayList after replace: " + top5Books);
  }

}

Output
ArrayList before replace: [Clean Code, Clean Coder, Effective Java, 
Head First Java, Head First Design patterns]
ArrayList after replace: [Clean Code, Introduction to Algorithms, 
Effective Java, Head First Java, Head First Design patterns]

You can see that initially, we have a list of 5 books and we have replaced the second element by calling the set(1, value) method, hence in the output, the second book which was "Clean Coder" was replaced by "Introduction to Algorithms".


That's all about how to replace existing elements of ArrayList in Java. The set() method is perfect to replace existing values just make sure that the List you are using is not immutable. You can also use this method with any other List type like LinkedList. The time complexity is O(n) because we are doing index-based access to the element.

Other ArrayList tutorials for Java Programmers
  • How to reverse an ArrayList in Java? (example)
  • How to loop through an ArrayList in Java? (tutorial)
  • How to synchronize an ArrayList in Java? (read)
  • How to create and initialize ArrayList in the same line? (example)
  • Difference between an Array and ArrayList in Java? (answer)
  • When to use ArrayList over LinkedList in Java? (answer)
  • Difference between ArrayList and Vector in Java? (answer)
  • How to get a sublist from ArrayList in Java? (example)
  • How to remove duplicate elements from ArrayList in Java? (tutorial)
  • How to sort an ArrayList in descending order in Java? (read)
  • Difference between ArrayList and HashSet in Java? (answer)
  • Difference between ArrayList and HashMap in Java? (answer)

Thanks for reading this tutorial so far. If you like this ArrayList replace example then please share it with your friends and colleagues. If you have any questions or feedback, please drop a note. 

8 comments:

  1. Great and clear Explanation!

    ReplyDelete
  2. What if you don't know the index and you want to update an item which meets certain criteria ?

    ReplyDelete
    Replies
    1. Hello @Unknown, in that case you need to iterate through the ArrayList and check every element.

      Delete
    2. how do you do that?

      Delete
    3. I think you can use a for-loop to find that certain item that matches certain criteria and then using the index from the for-loop you insert the item to the list at this index.

      Delete
    4. Yes, you can iterate through an ArrayList using Iterator, for-each or just for loop but becareful if you are removing elements as it can cause ConcurrentModficiationException. If you remove, just use Iterator.remove method instead of ArrayList.remove() method
      For example, you can check this post -how to remove dupolicate elements from arraylist

      Delete
  3. then, how can i do by giving the numbers inside arraylist how to replace it

    ReplyDelete
    Replies
    1. Can you explain your requirement bit more? What are you trying to do?

      Delete

Feel free to comment, ask questions if you have any doubt.