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
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
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:
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