Languages
[Edit]
EN

Java - modify items in ArrayList

0 points
Created by:
Tomeriko
203

In this article, we would like to show you how to modify items in the ArrayList in Java.

Quick solution:

myArrayList.set(index, element);

Where:

  • myArrayList - ArrayList name,
  • index - index of the element to replace,
  • element - element to be stored at the specified position.

 

Practical example

In this example, we modify items with the specified index (0 and 1) using set() method.

import java.util.ArrayList;

public class Example {

    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();

        // add items to the ArrayList
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        // modify/change items
        fruits.set(0, "Orange");
        fruits.set(1, "Kiwi");

        System.out.println(fruits);
    }
}

Output:

[Orange, Kiwi, Cherry]

References

Java Collections - ArrayList

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join