A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.w3resource.com/java-tutorial/arraylist/arraylist_set.php below:

Website Navigation


Java arraylist set method - w3resource

Java ArrayList.set() MethodLast update on August 19 2022 21:51:25 (UTC/GMT +8 hours) 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

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)


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4