Languages
[Edit]
EN

Java - modify items in ArrayList

0 points
Created by:
Tomeriko
383

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

Alternative titles

  1. Java - change items in ArrayList
  2. Java - replace items in ArrayList
  3. Java - update items in ArrayList
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

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