Java ArrayList.set()

 Posted On  | Yashwant Chavan 

In this tutorial you will learn about ArrayList.set() method. It is used replaces the element at the specified position in the list with the specified element.


Replaces the element at the specified position in this list with the specified element.

E java.util.ArrayList.set(int index, E element)


index index of the element to replace

element element to be stored at the specified position.


The element previously at the specified position


IndexOutOfBoundsException - throws IndexOutOfBoundsException exception if you try to set element at out of range position.

Java ArrayList.contains() example

Refer below steps

  • Constructs an empty ArrayList with an initial capacity using new ArrayList<String>().
  • Add some elements in colors ArrayList using add() method.
  • Call set() method to replace elements at 1st and 2nd positions.
  • Print List to verify the changes.

import java.util.ArrayList;

public class ArrayListSet {
    public static void main(String[] args) {

        ArrayList <String> colors = new ArrayList <String> ();

        System.out.println("Colors List before set():- " + colors);

        System.out.println("Old Element:- " + colors.set(1, "Yellow"));
        System.out.println("Old Element:- " + colors.set(2, "Light-Blue"));

        System.out.println("Colors List after set():- " + colors);


Colors List before set():- [Red, Green, Blue, White, Pink]
Old Element:- Green
Old Element:- Blue
Colors List after set():- [Red, Yellow, Light-Blue, White, Pink]

Promote your Blog, Website, or services on, My paypal id:

Payment will be accepted through paypal only.

© 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0199 seconds.