Replace element at specified index in Java ArrayList

import java.util.ArrayList;
import java.util.List;

public class ReplaceAnElementAtIndex {

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

		/*
		 * add() method appends the specified element to the end of given list.
		 */
		list.add(1);
		list.add(2);
		list.add(3);
		list.add(4);

		System.out.println("Elements in Original List");
		for (int i : list)
			System.out.println(i);

		/*
		 * Method E set(int index, E element) replaces the element at the
		 * specified position in list with the specified element.
		 * 
		 * Note*: It returns the element previously at the specified position.
		 */
		int replacedElement = list.set(2, 9);

		System.out.println("Replaced element is " + replacedElement);

		System.out.println("Elements in changed list are");
		for (int i : list)
			System.out.println(i);
	}
}

 

1 Comment Replace element at specified index in Java ArrayList

Leave A Comment

Your email address will not be published. Required fields are marked *