Java Tutorial: Array and ArrayList
Arrays are a sequential collection of objects or primitive values with a fixed-size. To create an empty array use
type var = new type[size] with
type being a class name and
size being an integer. Each item in the array has an index (location) starting from 0 to
size-1. An item can be referenced with
var[index] with index being an integer representing the location in the array.
1 2 3 4 5
Arrays can also be initialized using array literals to assign the array with values
The length of an array can be found with its
length variable which can be useful when traversing through the array.
Simple Array Traversal
This is a simple array traversal that uses a for loop
1 2 3
Traversal can also be done with a for-each loop. This makes traversal simpler to program but you lose access to item indexes.
1 2 3
Multi-dimensional arrays are arrays of arrays. When creating multi-dimensional arrays add as many sets of square-brackets as the amount of dimensions you are trying to setup.
Traversing multi-dimensional arrays can be done in a specific dimension or through all the items of the array. To traverse through all of the items, use nested for loops
1 2 3 4 5
When traversing through a specific dimension, use a loop on one dimension and set the indexes on the others
1 2 3
ArrayLists are a sequential collection of objects of a single type with a dynamic size. When using primitive types you have to reference its class name. To use ArrayLists you have to import the
java.util library. ArrayLists can be created with
ArrayList<Class> var new ArrayList<Class>();
Like arrays, ArrayLists use an indexing system that goes from 0 to
size()-1. However the size of the ArrayList is dynamic and can be found with the
Adding values to the end of the ArrayList can be done with the
add(item) method. Note that this will increase the size by 1.
We can also add items at a specific index within the ArrayList with
add(idx, item). Note that all items in the ArrayList starting at
idx and higher will be shifted up one index.
To access values at a specific index use the
You can override existing values in the ArrayList with
Deleting a value in the ArrayList can be done with
remove(idx). All items after
idx will have their index decreased by 1 and the size of the ArrayList will shrink
Traversal with ArrayLists is exactly the same as traversing arrays but when using a for-each loop remember to use the class name instead of primitive types
1 2 3 4 5 6 7