Write a Java program to update specific array element by given element
- We first import the java.util.* package, which contains the List and ArrayList classes that we will use in this program.
- We define a public class called Update_Element.
- We define the main method that takes an array of Strings as an argument.
- We create a new ArrayList object called list_Col with a type parameter of String.
- We add some elements to the list using the add method.
- We print the original list using System.out.println(list_Col).
- We update the element at index 1 with the value "Pink" using the set method.
- We update the element at index 4 with the value "Blue" using the set method.
- We print the updated list using System.out.println(list_Col).
Source Code
import java.util.*;
public class Update_Element
{
public static void main(String[] args)
{
List<String> list_Col = new ArrayList<String>();
list_Col.add("Black");
list_Col.add("Red");
list_Col.add("Orange");
list_Col.add("White");
list_Col.add("Green");
System.out.println(list_Col);
list_Col.set(1, "Pink");
list_Col.set(4, "Blue");
System.out.println(list_Col);
}
}
Output
[Black, Red, Orange, White, Green]
[Black, Pink, Orange, White, Blue]