ArrayList Methods

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.

ArrayLists

You can think of an ArrayList as a container that will resize as we add and remove objects from it.

"ArrayLists Example"

Creating ArrayLists

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:

ArrayList Methods

After creating and populating your ArrayList you can use multiple methods with it.

Adding to an ArrayList

To add a value to an ArrayList you use list.add(elem);. Here is an example using our classGrades and students ArrayLists:

Adding at a Specific Index

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:

Getting a Value

To get a value from your ArrayList you use list.get(index);. Here is an example using our classGrades and students ArrayLists:

Setting a Value

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:

Getting Size of an ArrayList

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:

Removing From ArrayList

Finally, we can remove a specific item from our ArrayList using list.remove(index);. Here is an example using our classGrades and students ArrayLists:

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

Last updated

Was this helpful?