What does the method set(int, obj o) do in java?


The set() method of the ArrayList class replaces the element at the specified position in this list with the specified element.

Example

import java.util.ArrayList;

public class Sample {
   public static void main(String args[]) {
      ArrayList al = new ArrayList();
      System.out.println("Initial size of al: " + al.size());
      al.add("C");
      al.add("A");
      al.add("E");
      al.add(1, "A2");
      System.out.println("Size of al after additions: " + al.size());
      System.out.println("Contents of al: " + al);
      System.out.println("Size of al after deletions: " + al.size());
      System.out.println("Contents of al: " + al);
      al.set(2, "new");
      System.out.println("Contents of al after setting the element: " + al);
   }
}

Output

Initial size of al: 0
Size of al after additions: 4
Contents of al: [C, A2, A, E]
Size of al after deletions: 4
Contents of al: [C, A2, A, E]
Contents of al after setting the element: [C, A2, new, E]

Updated on: 20-Feb-2020

70 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements