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

add()

Example

Insert an item into 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");

System.out.println(cars); } }

Definition and Usage

The add() method inserts an item into the list.

If an index is specified, the new item will be positioned at that index, pushing all subsequent elements in the list ahead by one.

If no index is provided, the new item will be added to the end of the list.

Syntax

Choose one from the following:

public boolean add(T item)
public void add(int index, T item)

T denotes the data type of elements in the list.

Parameter Values

Parameter

Description

index

Optional. The position in the list at which to add the item.

item

Required. The item to be added to the list.

Technical Details

Returns:

Nothing if an index is specified. When an index is not specified it returns true if the list changed and false if the list did not change.

Throws:

IndexOutOfBoundsException occurs if the index is negative or exceeds the list’s size.

More Examples

Example

Insert an item at a designated position within the 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.add(2, "Toyota");

System.out.println(cars); } }