Replacing ArrayList element with new value using set() method

In this article, we will discuss how to replace/update content of ArrayList using set method of List interface

This method replaces old value with new value

 

To replace ArrayList contents with new value :

Method signature:

Object set(int index, Object newObj);
  • This method is used to replace/update content of ArrayList element i.e.;
  • replacing old value with new value
  • returns old object value

ReplaceArrayListContentWithNewValue.java

package in.bench.resources.java.collections;

import java.util.ArrayList;

public class ReplaceArrayListContentWithNewValue {

	public static void main(String[] args) {

		// creating ArrayList object of type String
		ArrayList<String> tech = new ArrayList<String>();

		// adding elements to ArrayList object
		tech.add("Sun");
		tech.add("Apple");  
		tech.add("JBoss");  
		tech.add("BEA Weblogic");
		tech.add("Apache");

		// Iterating using for-loop
		System.out.println("Iterating ArrayList using for-loop\n");
		for(int index = 0; index < tech.size(); index++) {
			System.out.println("index-" + index + "  " + tech.get(index));
		}

		// replacing at 0-th index position
		tech.set(0, "Oracle");

		// replacing at 2-th index position
		tech.set(2, "Redhat");

		// replacing at 3-th index position
		tech.set(3, "Oracle Weblogic");

		// Iterating using enhanced for-loop
		System.out.println("\n\nIterating after replacing 3-elements\n");
		for(String tec : tech) {
			System.out.println(tec);
		}
	}
}

Output:

Iterating ArrayList elements using for-loop

index-0  Sun
index-1  Apple
index-2  JBoss
index-3  BEA Weblogic
index-4  Apache


Iterating after replacing 3-elements

Oracle
Apple
Redhat
Oracle Weblogic
Apache

Exception:

  • Trying to set value for out of range index, will throw IndexOutOfBoundsException
  • Index should be within range i.e.; 0 <= index < ArrayList size – 1
Exception in thread "main" java.lang.IndexOutOfBoundsException: 
Index: 6, Size: 5
	at java.util.ArrayList.rangeCheck(ArrayList.java:604)
	at java.util.ArrayList.set(ArrayList.java:397)
	at in.bench.resources.java.collections
.ReplaceArrayListContentWithNewValue.main
(ReplaceArrayListContentWithNewValue.java:32)

 

References:

 

Happy Coding !!
Happy Learning !!

Java - How to iterate through LinkedList in reverse-order ?
Java - Sorting ArrayList in Descending-order