Java Program to Update the List Items

In Java, Lists are dynamic collections that allow modifications, such as updating elements. We can use the set method to update the elements in the List. This method replaces the element at the given index with a new value, allowing modification of list contents.

In this article, we will learn to update the list items in Java using the set method.

Declaration:

public Object set(int index, Object element)

Return Value: The element that is at the specified index

Exception Throws: IndexOutOfBoundsException 
This occurs when the index is out of range.

index < 0 or index >= size()

Program to Update the List Items in Java

Below is the implementation to Update the List Items in Java:

Java
// Java program to update the list items 

// Importing required classes
import java.util.ArrayList;
import java.util.List;

// Main Class
public class UpdateList {

    // Main driver method
    public static void main(String[] args)
    {
        // Creating a list of courses
        List<String> courses = new ArrayList<>();

        // Adding courses to the list
        courses.add("Data Structures");
        courses.add("Algorithms");
        courses.add("Operating Systems");
        courses.add("DBMS");
        courses.add("Machine Learning");

        // Printing the original list of courses
        System.out.println("Original list: " + courses);

        // Updating the course at index 2
        courses.set(2, "Computer Networks");

        // Printing the updated list of courses
        System.out.println("Updated list: " + courses);
    }
}

Output
Original list: [Data Structures, Algorithms, Operating Systems, DBMS, Machine Learning]
Updated list: [Data Structures, Algorithms, Computer Networks, DBMS, Machine Learning]

Explanation of the above Program:

  • In the above code, we first create an ArrayList named ‘courses‘ and add five initial course names related to w3wiki.
  • We then print the original list of courses to the console to show the initial state of the list.
  • Next, we use the set method to update the course at index 2 from “Operating Systems” to “Computer Networks“.
  • Finally, we print the updated list of courses to the console to display the changes made to the list.

Complexity of the Above Method:

  • Time Complexity: O(1), where ‘set’ operation directly accesses the index
  • Auxiliary Space: O(1), because no extra space is used