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
Import ArrayList from
java.util
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 👍 |
---|---|
|
|
|
|
|
|
does not exit |
|
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
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.
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.
Change a value at an index
We can use → .set(INDEX, NEWVALUE)
to change a value at a certain location.
Remove a value at an index
We can use → .remove(INDEX)
to remove a value at a certain location.
Get the size of the ArrayList
We can use → .size()
to determine the number of elements in an ArrayList.
Check if a value exists in an ArrayList
We can use → .contains()
to determine if a value exists in an ArrayList.
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