Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
List equals() Method in Java with Examples
Next article icon

Java ArrayList set() Method

Last Updated : 12 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The set() method of the ArrayList class in Java is used to replace an element at a specified position with a new value. This is very useful when we need to update an existing element in an ArrayList while maintaining the list’s structure.

Example 1: Here, we will use the set() method to update an element in an ArrayList.

Java
// Update an element in an ArrayList import java.util.ArrayList;  public class GFG {     public static void main(String[] args) {                // Create an ArrayList and          // add elements         ArrayList<Integer> n = new ArrayList<>();         n.add(1);         n.add(2);         n.add(3);         n.add(4);         n.add(5);          // Print the original ArrayList         System.out.println("Before operation: " + n);          // Replace element at          // index 3 with 9         int r = n.set(3, 9);          System.out.println("After operation: " + n);         System.out.println("Replaced element: " + r);     } } 

Output
Before operation: [1, 2, 3, 4, 5] After operation: [1, 2, 3, 9, 5] Replaced element: 4 

Explanation: In the above example, it replaced an element in an ArrayList and prints both the updated list and the replaced element.

Syntax of ArrayList set() Method

public E set(int index, E element)

Parameters:

  • index: Index of the element to replace.
  • element: Element to be stored at the specified position.

Returns Value: It returns the element that was previously at the specified position.

Exception: IndexOutOfBoundsException: Thrown if the index is out of the valid range (index < 0 or index >= size).

Example 2: Here, this example will show how trying to replace an element at an invalid index results in an exception.

Java
// Handling IndexOutOfBoundsException import java.util.ArrayList;  public class GFG {     public static void main(String[] args) {         try {                        // Create an ArrayList and add elements             ArrayList<Integer> n = new ArrayList<>();             n.add(1);             n.add(2);             n.add(3);             n.add(4);             n.add(5);              // Print the original ArrayList             System.out.println("Before operation: " + n);              // Attempt to replace an element at an invalid index             n.set(7, 9);         } catch (IndexOutOfBoundsException e) {                        // Handle the exception             System.out.println("Exception: " + e);         }     } } 

Output
Before operation: [1, 2, 3, 4, 5] Exception: java.lang.IndexOutOfBoundsException: Index 7 out of bounds for length 5 


Next Article
List equals() Method in Java with Examples

R

RohitPrasad3
Improve
Article Tags :
  • Java
  • Java-ArrayList
  • Java-Collections
Practice Tags :
  • Java
  • Java-Collections

Similar Reads

  • Java List Interface
    The List Interface in Java extends the Collection Interface and is a part of the java.util package. It is used to store the ordered collections of elements. In a Java List, we can organize and manage the data sequentially. Key Features: Maintained the order of elements in which they are added.Allows
    15+ min read
  • List add() Method in Java with Examples
    The List add() method adds (appends) an element to a list. It can be used for both ArrayList and LinkedList. Example of List add() Method: Java Code // Java program to demonstrate // ArrayList usage import java.io.*; import java.util.ArrayList; import java.util.List; class GFG { public static void m
    3 min read
  • AbstractList set() Method in Java with Examples
    The set() method of java.util.AbstractList class is used to replace any particular element in the abstract list created using the AbstractList class with another element. This can be done by specifying the position of the element to be replaced and the new element in the parameter of the set() metho
    2 min read
  • List indexOf() Method in Java with Examples
    This method returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. Example: [GFGTABS] Java // Java Program to Implement List // indexOf() Method import java.util.*; class GFG { public static void main (String[] args) { // Lis
    2 min read
  • List lastIndexOf() Method in Java with Examples
    This method returns the last index of the occurrence of the specified element in this list, or -1 if this list does not contain the element. Example: [GFGTABS] Java // Java Program to demonstrate List // lastIndexOf() Method import java.util.*; class GFG { public static void main (String[] args) { /
    2 min read
  • List remove(Object obj) method in Java with Examples
    The remove(Object obj) method of List interface in Java is used to remove the first occurrence of the specified element obj from this List if it is present in the List. Example: [GFGTABS] Java // Java Program Illustrate List // remove(Element) Method import java.util.*; class GFG { public static voi
    3 min read
  • List get() method in Java with Examples
    The get() method of List interface in Java is used to get the element present in this list at a given specific index. Example: [GFGTABS] Java // Java Program to demonstrate List // get() Method import java.util.*; class Main { public static void main (String[] args) { // Create a List List<Intege
    2 min read
  • List contains() method in Java with Examples
    The contains() method of List interface in Java is used for checking if the specified element exists in the given list or not. Example: [GFGTABS] Java // Java Program to Demonstrate // List contains() Method import java.util.*; class GFG { public static void main (String[] args) { List<Integer
    3 min read
  • List add(int index, E element) method in Java
    The add(int index, E ele) method of List interface in Java is used to insert the specified element at the given index in the current list. Implementation: [GFGTABS] Java // Java code to illustrate add(int index, E elements) import java.util.*; public class ArrayListDemo { public static void main(Str
    2 min read
  • List addAll() Method in Java with Examples
    This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. Syntax: boolean addAll(Collection c) Parameters: This function has a single parameter, i.e, Collection c, whose elements are to be
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences