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);
	}
}

 

By | 2012-09-18T13:44:47+00:00 September 18th, 2012|Code Base|1 Comment

About the Author:

One Comment

  1. VIJAYA November 11, 2014 at 7:04 am - Reply

    Its really helpful for me..

Leave A Comment