ArrayList set(int index E element) method in java

Let’s learn ArrayList set(int index, E element) method in java.

ArrayList set(int index, E element) method in java

set(int index, E element) method replaces the element at the specified position in this list with the specified element.

Syntax:

public E set(int index, E element)

Parameters:

index index of the element to replace.

element element to be stored at the specified position.

Throws:

IndexOutOfBoundsException – if the index is out of range(index < 0 || index >= size()).

Now let’s see example on ArrayList set(int index, E element) method.

import java.util.ArrayList;
public class ArrayListSetMethodExample
{
   public static void main(String[] args)
   {
      ArrayList<String> names = new ArrayList<String>(5);
      names.add("vinay");
      names.add("ajay");
      names.add("vijay");
      names.add("bharat");
      names.add("dinesh");
      System.out.println("ArrayList before using set() method: " + names);
      // change vijay name to chandan
      System.out.println("ArrayList after using set() method: ");
      names.set(2, new String("chandan"));
      for(int a = 0; a < 5; a++)
      {
         System.out.println(names.get(a).toString());
      }
   }
}

Output:

ArrayList before using set() method: [vinay, ajay, vijay, bharat, dinesh]
ArrayList after using set() method:
vinay
ajay
chandan
bharat
dinesh


Let’s see example on ArrayList set(int index, E element) method for IndexOutOfBoundsException.

import java.util.ArrayList;
public class ArrayListSetMethodExample
{
   public static void main(String[] args)
   {
      try
      {
         ArrayList<Integer> al = new ArrayList<Integer>();
         al.add(36);
         al.add(23);
         al.add(39);
         al.add(69);
         al.add(56);
         System.out.println("ArrayList before using set() method: " + al);
         // replace number at the index 7 with 25
         System.out.println("Trying to replace the element at index greater than capacity: ");
         int num = al.set(7, 25);
         // printing modified ArrayList
         System.out.println("ArrayList after using set() method: " + al);
         // printing replaced element
         System.out.println("Replaced number: " + num);
      }
      catch(IndexOutOfBoundsException ex)
      {
         System.out.println("Exception: " + ex);
      }
   }
}

Output:

ArrayList before using set() method: [36, 23, 39, 69, 56]
Trying to replace the element at index greater than capacity:
Exception: java.lang.IndexOutOfBoundsException: Index 7 out of bounds for length 5


Also read – java overview