ArrayList Methods
Last updated
Was this helpful?
Last updated
Was this helpful?
Arrays are amazing tools! Unfortunately, they lack flexibility and useful methods. That's where ArrayList comes into play. An ArrayList is similar to an Array, except it is resizable and has more functionality.
You can think of an ArrayList as a container that will resize as we add and remove objects from it.
They way we create an ArrayList varies from the way we create an Array. To create an ArrayList we use: ArrayList<type> variableName = new ArrayList<type>();
. It is also import to know ArrayLists can't store primitive types, so we must use Integer
for ints and Double
for doubles
Lets say we want to create an ArrayList that holds the grades for a class. Here is an example of what that code will look like:
Now we want to create a list of students in a classroom. We can use the ArrayList for this as well:
After creating and populating your ArrayList you can use multiple methods with it.
To add a value to an ArrayList you use list.add(elem);
. Here is an example using our classGrades
and students
ArrayLists:
ArrayLists also allow us to add an item at a specific index using list.add(index, elem);
. Here is an example using our classGrades
and students
ArrayLists:
To get a value from your ArrayList you use list.get(index);
. Here is an example using our classGrades
and students
ArrayLists:
With ArrayLists we can set a specific index's value using list.set(index, value);
. Here is an example using our classGrades
and students
ArrayLists:
We can also access the length or size of a specific ArrayList using list.size();
. Here is an example using our classGrades
and students
ArrayLists:
Finally, we can remove a specific item from our ArrayList using list.remove(index);
. Here is an example using our classGrades
and students
ArrayLists:
As with traditional Arrays, we can iterate over ArrayLists.
We can use a regular for loop to iterate over our ArrayList like:
We also have the option of using a For Each loop to iterate over our ArrayList like: