ArrayList

An ArrayList in Java is a dynamic array that can hold elements of any data type.

Unlike a static array in Java, an ArrayList can be resized dynamically. This means that we can add and remove values from an ArrayList.

An ArrayList is a class in the Java Collection framework that is part of the java.util package

Java ArrayList Requirements

  1. Import ArrayList from java.util

  1. Create an ArrayList object

The data type of the ArrayList's items must be OBJECTS. Moreover, they should be Generic/Wrapper Class not primitive data types.

Primitive Data Type πŸ‘Ž
Wrapper Class Equivalent πŸ‘

int

Integer

double

Double

boolean

Boolean

does not exit

String

In Java, whenever we need data to be β€œobjects” we have a Wrapper class to represent built-in data to be β€œobjects”.

Common ArrayList Methods

  1. Add an item to an ArrayList

We can use β†’ .add() to add a value to an ArrayList to the END OF THE ARRAYLIST.

What happens if you want to add a value at a certain index?

.add(int index, value) can be also be used to add values to your ArrayList at certain locations following the rules/concepts below:

Rule A: Valid Index Range

The index provided must be within the range of 0 to the size of the ArrayList (inclusive). If the index is outside this range, it will throw an IndexOutOfBoundsException.

Rule B:. Shift Existing Elements

When you add an element at a specific index, all elements at that index or greater are shifted one position to the right.

Rule C. Capacity Check and Resize

If adding an element exceeds the current capacity of the ArrayList, it will automatically increase its capacity to accommodate the new element. This involves creating a new array with a larger capacity, copying the existing elements into the new array, and then adding the new element.

More reading on ArrayList Sizing

  1. Grab a value from an ArrayList

We can use β†’ .get(INDEX) to grab value at a positive integer index value. (Index starts at zero always)

You can get an error if the index does not exist.

  1. Change a value at an index

We can use β†’ .set(INDEX, NEWVALUE) to change a value at a certain location.

  1. Remove a value at an index

We can use β†’ .remove(INDEX) to remove a value at a certain location.

  1. Get the size of the ArrayList

We can use β†’ .size() to determine the number of elements in an ArrayList.

  1. Check if a value exists in an ArrayList

We can use β†’ .contains() to determine if a value exists in an ArrayList.

  1. Determine the index of a value in an ArrayList

We can use β†’ .indexOf() to determine an index of a value in an ArrayList. Returns -1 if not found.

We can use β†’ .lastIndexOf() to determine an index of a value in an ArrayList from the right. Returns -1 if not found.

ArrayLists are printable!

Output:

As long as the ArrayList contains primitive equivalent wrapper class items, we can simply print the ArrayList within System.out.println().

Last updated