Wednesday 25 July 2012

Replace an element at specified index of Java ArrayList Example


This Java Example shows how to replace an element at specified index of java ArrayList object using set method.


import java.util.ArrayList;

public class ReplaceElementAtSpecifiedIndexArrayListExample {

	public static void main(String[] args) {

		// create an ArrayList object
		ArrayList arrayList = new ArrayList();

		// Appends the specified element to the end of this list.

		arrayList.add("1");
		arrayList.add("2");
		arrayList.add("3");

		System.out.println("ArrayList contains...");

		// display elements of ArrayList
		for (int index = 0; index < arrayList.size(); index++)
			System.out.println(arrayList.get(index));

		/*
		 * To replace an element at the specified index of ArrayList use Object
		 * set(int index, Object obj) method. This method replaces the specified
		 * element at the specified index in the ArrayList and returns the
		 * element previously at the specified position.
		 */
		Object replaced = arrayList.set(1, "REPLACED ELEMENT");

		System.out.println(replaced + " is replaced with new element.");

		System.out.println("Modified ArrayList contains...");

		// display elements of ArrayList
		for (int index = 0; index < arrayList.size(); index++)
			System.out.println(arrayList.get(index));

	}
}


The output is:



ArrayList contains...
1
2
3
2 is replaced with new element.
Modified ArrayList contains...
1
REPLACED ELEMENT
3

No comments:

Post a Comment