To change the value of an element in an ArrayList
in Java, you can use the set
method of the ArrayList
class.
Here's an example of how you might do this:
import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); list.add("cherry"); list.set(1, "orange"); // Change the second element to "orange" System.out.println(list); // Output: [apple, orange, cherry] } }Source:wuttual.wwri.com
In this example, the set
method is used to change the value of the second element in the ArrayList
from "banana" to "orange".