w3resource

Java ArrayList.set() Method

public E set(int index, E element)

The ArrayList.set() method is used to set an element in an ArrayList object at the specified index.

Package: java.util

Java Platform: Java SE 8

Syntax:

set(int index,E element)

Parameters:

Name Description Type
index The index of the element to be set. int
element Element to be stored at the specified position.  

Return Value:
The element that previously existed at the specified index.

Throws:
IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())

Pictorial presentation of ArrayList.set() Method

Java ArrayList.set() Method

Example: ArrayList.set() Method

The following example shows the usage of java.util.Arraylist.set() method method.

import java.util.*;

public class test {
   public static void main(String[] args) {
      
    // create an empty array list with an initial capacity
    ArrayList<String> color_list = new ArrayList<String>(5);

    // use add() method to add values in the list
    color_list.add("White");
    color_list.add("Black");
    color_list.add("Red");
    color_list.add("White");
	color_list.add("Yellow");
	    
	// Change the Red color to Violet 
    color_list.set(2, new String("Violet"));		
	
	// Print out the colors in the ArrayList
    for (int i = 0; i < 5; i++)
      {
         System.out.println(color_list.get(i).toString());
      }
  }
}   

Output:

F:\java>javac test.java

F:\java>java test
White
Black
Violet
White
Yellow

Example of Throws: set() Method
IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size()).

Let

(index < -1 || index >= size());

in the above example.

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBou
ndsException: -1                                       
        at java.util.ArrayList.elementData(ArrayList.ja
va:400)                                                
        at java.util.ArrayList.get(ArrayList.java:413) 
        at test.main(test.java:22) 

Java Code Editor:

Previous:get Method
Next:add Method (Object)



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-tutorial/arraylist/arraylist_set.php