Arraylist

Introduction

ArrayList is a collection similar to array but with dynamic size.

Simply it's size is not defined during initialization and changes when element is added / removed.

In order to use it the following line should be added:

Syntax

type specifies the values type - Integer, Double, String etc...

Initialization

Adding element to the back

This can be done via the add function. Like in the following code:

Accessing specific index

Accessing element at specific index is done via the get function.

Let's add elements to ArrayList and access the element at index 1.

Output:

Outside of bounds

Accessing element outside of ArrayList's bounds results in exception.

Let's look at the following example

numbers has 3 elements (indexes from 0 to 2) but at line 11 the 3rd index is accessed.

Size

Size is the count of elements in collection.

In order to get it the size function is used.

Example:

Output:

Looping elements

Let's have an ArrayList of ages and print only those who are greater than 20.

Output: