Java ArrayList set()
method is used to replace an existing element present in the ArrayList at the specified position with the new given element. The syntax of the set()
method is:
public E set(int index, E element)
In this syntax:
index
: This specifies the position of the element which needs to be replaced.element
: The new element which will replace the existing element.
Note: The method returns the element (old element) which is replaced.
Example
Let’s see how to use the set()
method to replace an existing element in the ArrayList.
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
// Create an ArrayList and add some elements
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");
list.add("Mango");
System.out.println("Original list: " + list);
// Replacing the second element (element at index 1)
String oldElement = list.set(1, "Blueberry");
System.out.println("Replaced element: " + oldElement);
System.out.println("Updated list: " + list);
}
}
Output:
Original list: [Apple, Banana, Orange, Mango]
Replaced element: Banana
Updated list: [Apple, Blueberry, Orange, Mango]
In this example:
- We have an ArrayList of String type that contains the fruits.
- We have used set() method to replace second element (index 1) of the list.
- As we discussed earlier, this method returns the element which is getting replaced. In this case, it retuned element “Banana” as this is replaced with “Blueberry”.
- In the end, we printed the updated list with new element.
Example 2
In this example, we have an ArrayList of Integer type. Let’s replace the elements using set() method.
import java.util.ArrayList;
public class SetExample {
public static void main(String args[]) {
ArrayList<Integer> arraylist = new ArrayList<>();
arraylist.add(1);
arraylist.add(2);
arraylist.add(3);
arraylist.add(4);
arraylist.add(5);
arraylist.add(6);
arraylist.add(7);
System.out.println("ArrayList before update: "+arraylist);
//Updating 1st element
arraylist.set(0, 11);
//Updating 2nd element
arraylist.set(1, 22);
//Updating 3rd element
arraylist.set(2, 33);
//Updating 4th element
arraylist.set(3, 44);
//Updating 5th element
arraylist.set(4, 55);
System.out.println("ArrayList after Update: "+arraylist);
}
}
Output:
ArrayList before update: [1, 2, 3, 4, 5, 6, 7] ArrayList after Update: [11, 22, 33, 44, 55, 6, 7]
Leave a Reply