Lesson Overview

Welcome aboard our Java Voyage! Today, we're learning about ArrayLists. They're similar to arrays but can resize dynamically and also have many additional ways to simplify our lives. By the end, you'll know how to create and manipulate an ArrayList and understand when it's preferable to use arrays.

Creating an ArrayList in Java

ArrayLists are akin to a flexible roster of interstellar explorers; their size changes as we encounter or lose crew members. ArrayLists, part of Java's Collections Framework, elevate arrays to another level by providing more flexibility.

Constructing an ArrayList is akin to assembling a crew list. As shown, we declare a variable of type ArrayList:

List<Integer> crewMembers = new ArrayList<>(); // creating an empty list
List<Integer> members = Arrays.asList(1, 2, 3, 4, 5); // creating a pre-defined list

Here:

  • List<Integer> is a general type for all lists of integers
  • crewMembers is a list name
  • new ArrayList<>() creates an instance of the list of integers. Note the <> part denoting that ArrayList can be of any type (Float, String, etc.), but we already specified the type when mentioning it'd be List<Integer> at the beginning of the definition.
  • Arrays.asList declares a pre-defined list of integers.

Did you notice we used List<Integer> as a type, not ArrayList<Integer>? This is called abstraction, as List<Integer> is an interface for all lists. There is no need to understand it in detail for now, though - we'll cover it in the next courses!

Accessing ArrayList Elements

Now, let's engage with our crew. ArrayLists provide methods such as:

  • add(element) - to add a new element to the end of the list.
  • get(int index) - for accessing element at the given position index, starting from 0, as in arrays.
  • set(index, value) - for updating the value at the given position index, with a new value.
  • remove(index) - remove the element at the given position index.
  • size() - is used to determine how many elements are in the list.
crewMembers.add(101); // Add a crew member
crewMembers.add(102); // Add another crew member

System.out.println(crewMembers.get(0)); // Output: 101. Retrieves the first crew member
System.out.println(crewMembers.size()); // Output: 2. Finds the total number of crew members
System.out.println(crewMembers); // Output: [101, 102]

// Removing the 2nd element, the `crewMembers` list now contains a single element 101
crewMembers.remove(1);
System.out.println(crewMembers); // Output: [101]
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal