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.LinkedList;
public class Main { 
  public static void main(String[] args) { 
    LinkedList<String> cars = new LinkedList<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 exchanges an item at a designated position in the list and returns the item that previously occupied that position.

Syntax

public T set(int index, T item)

T represents the data type of items within the list.

Parameter Values

Parameter

Description

index

Mandatory. The index of the item to be substituted.

Item

Mandatory. The new item to replace the one at the specified position.

Technical Details

 

Returns:

The item that previously occupied the designated position in the list.

Throws:

IndexOutOfBoundsException occurs if the index is less than zero, equal to the size of the list, or greater than the size of the list.