Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java ArrayList add() Method

Java ArrayList add() Method

Java ArrayList Java ArrayList

The add() method inserts an element into the dynamic array at the specified position.

The syntax of the add() method is:


arraylist.add(int index,E element)

**Note:** arraylist is an object of the ArrayList class.

Parameter Description:

If no actual argument is passed for index, the element will be appended to the very end of the array.

Return Value

If the element is inserted successfully, returns true.

Note: If index is out of range, the add() method throws an IndexOutOfBoundsException exception.

Example

Inserting elements using the ArrayList add() method:

Example

import

java.util.ArrayList

;

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Create an array

        ArrayList

<

Integer

primeNumbers

=

new

ArrayList

<>

(

)

;

       

// Insert elements into the array

        primeNumbers.

add

(

2

)

;

        primeNumbers.

add

(

3

)

;

        primeNumbers.

add

(

5

)

;

       

System

.

out

.

println

(

"ArrayList: "

primeNumbers

)

;

   

}

}

The output of the above program is:

ArrayList: [2, 3, 5]

In the example above, we created an array named primeNumbers. Here the optional parameter index is not passed to the add() method. Therefore, all elements are inserted at the end of the array.

Inserting an element at a specified position:

Example

import

java.util.ArrayList

;

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Create an array

        ArrayList

<

String

sites

=

new

ArrayList

<>

(

)

;

       

// Insert an element at the end of the array

        sites.

add

(

"Google"

)

;

        sites.

add

(

"Runoob"

)

;

        sites.

add

(

"Taobao"

)

;

       

System

.

out

.

println

(

"ArrayList: "

sites

)

;

       

// Insert an element at the first position

        sites.

add

(

1

,

"Weibo"

)

;

       

System

.

out

.

println

(

"Updated ArrayList: "

sites

)

;

   

}

}

The output of the above program is:

ArrayList: [Google, Runoob, Taobao]
更新 ArrayList: [Google, Weibo, Runoob, Taobao]

In the example above, we used the add() method to insert elements into the array.

Please note this line:

sites.add(1, "Weibo");

We already know that the index parameter in the add() method is optional. So Weibo is inserted at the array index position 1.

Note: So far, we have only added single elements. However, we can also use the addAll() method to add multiple elements from a collection (arraylist, set, map, etc.) to an array. To learn more, please visit Java ArrayList addAll() .

Java ArrayList Java ArrayList