Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

set()

Example

Substitute an item in a list.

import java.util.ArrayList;
public class Main {
  public static void main(String[] args) {
    ArrayList<String> cars = new ArrayList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");
    cars.set(0, "Opel");
    System.out.println(cars);
  }
}

Definition and Usage

The set() method replaces an item at a specified position in the list and returns the item previously at that position.

Syntax

public T set(int index, T item)

T denotes the data type of the items in the list.

Parameter Values

Parameter

Description

index

Required: The index of the item to be replaced.

item

Required: The new item to be inserted at the specified position.

Technical Details

Returns:

The item that was previously located at the specified position in the list.

Throws:

IndexOutOfBoundsException occurs if the index is negative, equal to the list’s size, or greater than the list’s size.