Update Elements in ArrayList by Index in Kotlin | Kotlin ArrayList set Function

The set function in Kotlin is used to replace the element at a specified index in an ArrayList with a new element. This function is part of the Kotlin standard library and provides a convenient way to update elements in a list.

Table of Contents

  1. Introduction
  2. set Function Syntax
  3. Understanding set
  4. Examples
    • Basic Usage
    • Updating Elements in a List
    • Handling IndexOutOfBoundsException
  5. Real-World Use Case
  6. Conclusion

Introduction

The set function allows you to replace an element at a specified index in an ArrayList with a new element. This is useful for scenarios where you need to update specific elements in a list.

set Function Syntax

The syntax for the set function is as follows:

operator fun <T> ArrayList<T>.set(index: Int, element: T): T

Parameters:

  • index: The position of the element to be replaced.
  • element: The new element to be set at the specified index.

Returns:

  • T: The element that was previously at the specified index.

Understanding set

The set function replaces the element at the specified index in the ArrayList with the new element provided. It returns the element that was previously at the specified index. If the index is out of bounds, the function throws an IndexOutOfBoundsException.

Examples

Basic Usage

To demonstrate the basic usage of set, we will create an ArrayList and replace elements at specific positions.

Example

fun main() {
    val numbers = arrayListOf(10, 20, 30, 40, 50)
    println("Original list: $numbers")

    val oldElement = numbers.set(2, 35)
    println("Updated list: $numbers")
    println("Replaced element: $oldElement")
}

Output:

Original list: [10, 20, 30, 40, 50]
Updated list: [10, 20, 35, 40, 50]
Replaced element: 30

Updating Elements in a List

This example shows how to use set to update elements in an ArrayList.

Example

fun main() {
    val fruits = arrayListOf("Apple", "Banana", "Cherry", "Date")
    println("Original list: $fruits")

    fruits.set(1, "Blueberry")
    fruits.set(3, "Dragonfruit")
    println("Updated list: $fruits")
}

Output:

Original list: [Apple, Banana, Cherry, Date]
Updated list: [Apple, Blueberry, Cherry, Dragonfruit]

Handling IndexOutOfBoundsException

This example demonstrates how to handle IndexOutOfBoundsException when updating an element at an invalid index.

Example

fun main() {
    val colors = arrayListOf("Red", "Green", "Blue")
    try {
        colors.set(3, "Yellow")
    } catch (e: IndexOutOfBoundsException) {
        println("Exception: ${e.message}")
    }
}

Output:

Exception: Index 3 out of bounds for length 3

Real-World Use Case

Updating User Information

In real-world applications, the set function can be used to update user information in a list, such as changing the email address of a user.

Example

data class User(val id: Int, var name: String, var email: String)

fun main() {
    val users = arrayListOf(
        User(1, "Alice", "alice@example.com"),
        User(2, "Bob", "bob@example.com"),
        User(3, "Charlie", "charlie@example.com")
    )
    println("Original users: $users")

    users.set(1, User(2, "Bob", "newbob@example.com"))
    println("Updated users: $users")
}

Output:

Original users: [User(id=1, name=Alice, email=alice@example.com), User(id=2, name=Bob, email=bob@example.com), User(id=3, name=Charlie, email=charlie@example.com)]
Updated users: [User(id=1, name=Alice, email=alice@example.com), User(id=2, name=Bob, email=newbob@example.com), User(id=3, name=Charlie, email=charlie@example.com)]

Conclusion

The set function in Kotlin is a powerful and flexible way to update elements in an ArrayList. It allows you to replace elements at specified indices, making it useful for various applications, including data management and task handling. 

By understanding and using the set function, you can effectively manage and manipulate ArrayList collections in your Kotlin applications.

Comments