Start learning free

LESSON 100 OF 671 · ARRAYS I

ArrayList in Java

Lesson

A big limitation of static arrays in Java is the fact that once the array is created, it has a fixed size.

The ArrayList overcomes this limitation by having variable size and allowing for elements to be added or removed.


Creation:

We create an ArrayList by using the keywords new and ArrayList, then writing the type of the elements inside <> followed by paranthesis:

new ArrayList<String>();

This code creates an empty ArrayList where each item is a String.


Casting:

A good practice is to cast the created ArrayList in its interface by using a List variable and specifying there the type of the elements, like this:

List<String> sandwich = new ArrayList<>();

Initialization:

You can also initialize an ArrayList at creation by using the List.of() function and put a comma between each entry, like this:

List<String> sandwich = new ArrayList<>(
    List.of("peanut butter", "jelly", "bread")
);

We created an ArrayList named sandwich which consits of 3 items: "peanut butter", "jelly" and "bread".


Assignment
Follow the Coding Tutorial and let's create some ArrayLists!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check