Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

November Discount Launch 2022 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:

>> GET ACCESS NOW

November Discount Launch 2022 – TEMP TOP (NPI)
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:

>> GET ACCESS NOW

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

1. Overview

Through this tutorial, we'll take a look at how to replace an element at a specific index in a Java ArrayList.

2. Common Practice

To replace an existing element, First, we need to find the exact position of that element in the ArrayList. This position is what we call the index. Then, we can replace the old element with a new one.

The most common way to replace an element in Java ArrayList is to use the set (int index, Object element) method. The set() method takes two parameters: the index of the existing item and the new item.

The index of an ArrayList is zero-based. Thus, to replace the first element, 0 must be the index passed as a parameter.

The IndexOutOfBoundsException will occur if the provided index is out of bounds.

3. Implementation

Let's see through an example how to replace an element in Java ArrayList at a specific index.

List<Integer> EXPECTED = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

List<Integer> aList = new ArrayList<>(Arrays.asList(1, 2, 7, 4, 5));
aList.set(2, 3);

assertThat(aList).isEqualTo(EXPECTED);

First, we create an ArrayList with five elements. Then, we replace the third element with the value 7, having index 2 with 3. Finally, we can see that index 2 with value 7 is removed from the list and updated with the new value 3. Also, note that the list size is not impacted.

4. Conclusion

In this quick article, we learned how to replace an element at a specific index in Java ArrayList. Furthermore, you can use this method with any other List type like LinkedList. Just make sure that the List you are using is not immutable.

As always, the complete source code for this article can be found over on GitHub.

November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:

>> GET ACCESS NOW

Generic footer banner
Comments are closed on this article!