Home » Java ArrayList add() method with Examples

Java ArrayList add() method with Examples

by Online Tutorials Library

Java ArrayList add method

Java ArrayList add(E element) method

The ArrayListadd(E element) methodof Java ArrayList classappends a new value to the end of this list.

Syntax:

Parameter:

Here, “element” is an element to be appended to the list.

Return:

It always return “true”. Don’t worry about the Boolean return value. It always there as other classes in the collections family need a return value in the signature when adding an element.

Example 1

Test it Now

Output:

[element1, true, last element]  

Example 2

Test it Now

Output:

does not compile.  

This time the compiler knows that only Integer values are allowed in and prevents the attempt to add a String value.

Java ArrayList add(int index, E element) method

The add(int index, E element) method of Java ArrayList class inserts a specific element in a specific index of ArrayList. It shifts the element of indicated index if exist and subsequent elements to the right.

Syntax:

Parameter:

“index”: index at which the element will be inserted.

“element”: is an element to be inserted.

Return:

Return nothing.

Example 3

Test it Now

Output:

["black", "red" , "white", "blue"]  

Example 4

Test it Now

Output:

[1, "e1", "e2" , 1]  

Example 5

Test it Now

Output:

throwsIndexOutOfBoundsException  

Next TopicJava ArrayList

You may also like