How to Replace ArrayList Element at Specified Index in Java


In this example, we’ll learn how to replace an element of java ArrayList object at specified index with set method.

Source Code

package com.beginner.examples;

import java.util.ArrayList;

public class ReplaceArrayListElementExample {

	public static void main(String[] args) {
		ArrayList al = new ArrayList();

		al.add("a");
		al.add("b");
		al.add("c");
		al.add("E");

		// This method returns the old element
		String oldElem = al.set(3, "e");

		System.out.println(al+"n"+oldElem);
	}
}

Output:

[a, b, c, e]
E

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments