Java — ArrayList set() method in Java | Code Factory

public E set(int index, E element)
  • index- index of the element to replace
  • element- element to be stored at the specified position
package com.example.java.programming;import java.util.ArrayList;/**
* @author code.factory
*
*/
public class ArrayListSetExample {
public static void main(String... args) {
try {
// Creating object of ArrayList<Integer>
ArrayList<Integer> arryList = new ArrayList<Integer>();
// Populating arryList
arryList.add(1);
arryList.add(2);
arryList.add(3);
arryList.add(4);
arryList.add(5);
// print arryList
System.out.println("Before operation: " + arryList);
// Replacing element at the index 3 with 30 using method set()
int i = arryList.set(3, 30);
// Print the modified arryList
System.out.println("After operation: " + arryList);
// Print the Replaced element
System.out.println("Replaced element: " + i);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
}
Before operation: [1, 2, 3, 4, 5]
After operation: [1, 2, 3, 30, 5]
Replaced element: 4
package com.example.java.programming;import java.util.ArrayList;/**
* @author code.factory
*
*/
public class ArrayListSetExample {
public static void main(String... args) {
try {
// Creating object of ArrayList<Integer>
ArrayList<Integer> arryList = new ArrayList<Integer>();
// Populating arryList
arryList.add(1);
arryList.add(2);
arryList.add(3);
arryList.add(4);
arryList.add(5);
// print arryList
System.out.println("Before operation: " + arryList);
// Replacing element at the index 6 with 30 using method set()
int i = arryList.set(6, 30);
// Print the modified arryList
System.out.println("After operation: " + arryList);
// Print the Replaced element
System.out.println("Replaced element: " + i);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
}
Before operation: [1, 2, 3, 4, 5]
java.lang.IndexOutOfBoundsException: Index: 6, Size: 5
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.set(ArrayList.java:444)
at com.example.java.programming.ArrayListSetExample.main(ArrayListSetExample.java:27)

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to make your life easy with Python executable?

Linux Loops and Functions

{UPDATE} Fashion Model spa,Makeover,Dressup free girls games. Hack Free Resources Generator

Connect Salesforce CRM with -> Markting cloud using Markting Cloud Connect

Serverless Jenkins with Jenkins X

Identity Management with AWS Cognito in SpringBoot Application.

Command AWS through CLI

Methodology for implementing an RPA approach — Pilot

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Code Factory

Code Factory

More from Medium

Java OOPS Concepts

Annotations In Java

HashMap in Java

Java Optional