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.

syntax

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

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

Parameter

index index of the element to replace

element element to be stored at the specified position.

Return

The element previously at the specified position

Return

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.
package com.technicalkeeda.app;

import java.util.ArrayList;

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

        ArrayList <String> colors = new ArrayList <String> ();
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");
        colors.add("White");
        colors.add("Pink");

        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);
    }
}

Output

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 technicalkeeda.com, My paypal id: yashwantchavan@gmail.com

Payment will be accepted through paypal only.


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0199 seconds.