CodeGym /Courses /JAVA 25 SELF /“Infinite array” — ArrayList<T>

“Infinite array” — ArrayList<T>

JAVA 25 SELF
Level 12, Lesson 1
Available

1. Introduction

This is the first lecture of the bonus level. We have already come very close to studying OOP. And I want to whet your interest and peek a little ahead 😈. At the current level I will tell you about 5 interesting things:

  1. ♾️ You will learn to create infinite arrays
  2. 📖 Then keep a “personal dictionary”
  3. 💾 After that I will give you a brief introduction to working with files
  4. 🌐 Then we will learn to download images from the internet
  5. 🛰️ And in the final lecture of the level you will track the International Space Station (ISS) in real time

How all this works under the hood you will learn in future levels, and today you will simply learn to use the tools I provide. Intrigued? Then let’s begin 😇.

Reviewing regular arrays

Let’s recall a regular array in Java:

int[] arr = new int[10];

A great thing, but it has a couple of limitations: the size is fixed; you can’t add or remove an element unless you create a new array. And sometimes you want an array that grows and shrinks as needed. And we have an excellent solution — the dynamic array ArrayList!

ArrayList is a “smart array” that can grow and shrink automatically. Unlike a regular array, where the size is fixed, ArrayList itself makes sure there is enough space for new elements.

Creating an infinite array

To create our ArrayList, you need to write code like:

ArrayList<String> array = new ArrayList<String>()

After that you can add elements to it:

array.add("Masha");
array.add("Katya");

Creating a dynamic array for integers

As you may have guessed, the element type of our dynamic array must be specified in angle brackets. You can specify any type except primitive types. Primitive types must be replaced with their wrapper types.

Example:

ArrayList<Integer> numbers = new ArrayList<Integer>();      // int
ArrayList<Double> fees = new ArrayList<Double>();            // double
ArrayList<Boolean> yesList = new ArrayList<Boolean>();       // boolean
ArrayList<Character> chars = new ArrayList<Character>();     // char

Our ArrayList does not support [index] to access elements, but it has special methods that cover all your needs. Let’s go through the most interesting ones.

2. Method add(element) — adding an element

The first thing we do with a list is add data to it. For this we use the add method. It puts an element at the end of the list.

ArrayList<String> todo = new ArrayList<>(); // to-do list
todo.add("Learn ArrayList");
todo.add("Make tea");
todo.add("Go for a walk");

After these three lines we have a list of three strings. Unlike an array, we don’t need to specify the size in advance — it grows on its own as you add elements.

Very convenient: you can start with an empty list and gradually fill it depending on user actions or the program’s input data.

3. Method get(index) — index access

Each element of a list has its ordinal number — the index. Indexing always starts from zero. That is, the first element has number 0, the second has number 1, and so on.

If we want to get an element by its number, we use the get method.

String task = todo.get(1);
System.out.println("Second task: " + task);

Output:

Second task: Make tea

It’s important to remember: if you access an index that doesn’t exist (for example, todo.get(10) with a list of three elements), the program will throw an IndexOutOfBoundsException. Therefore you should either be sure about the index or check the list size via size().

4. Method set(index, element) — replacing an element

Sometimes you need to replace an element in the list. In this case you don’t need to delete and add it again — just use the set method.

todo.set(1, "Brew coffee"); 
System.out.println("Now the second task: " + todo.get(1));

Output:

Now the second task: Brew coffee

Thus, set is a way to update a list “on the fly”.

5. Method remove(index) — deleting an element

You can delete an element from an ArrayList by its index.

todo.remove(0); 
System.out.println("First task now: " + todo.get(0));

Output:

First task now: Brew coffee

We removed the first element (index 0). And now the second became the first, and the one that used to be third became the second. An important point: after deletion the list elements shift.

This can sometimes be surprising for beginners. Always keep in mind that after deletion the indices are recalculated.

6. Method size() — get the list size

The size method returns the number of elements in the list. This is similar to the length property in arrays, but in ArrayList it’s a method.

System.out.println("Total tasks: " + todo.size());

Output:

Total tasks: 2

Often size is used in loops to iterate over all elements:

for (int i = 0; i < todo.size(); i++) 
{
    System.out.println(todo.get(i));
}

7. Method contains(element) — presence check

To find out whether the list contains a needed element, you can use contains. This method returns true or false.

System.out.println(todo.contains("Go for a walk"));
System.out.println(todo.contains("Make tea"));

Output:

true
false

A very useful method when you want to avoid duplicates or check the condition “whether such an element exists in the list”.

8. Iterating over elements

There are two ways to traverse a list.

Index-based loop

This method is needed if the element’s number matters to you.

for (int i = 0; i < todo.size(); i++) 
{
    System.out.println(i + ": " + todo.get(i));
}

For-each loop

And if the number is not needed and you just want to see all elements — use a for-each loop.

for (String task : todo) 
{
    System.out.println("Task: " + task);
}

Such a loop is shorter and easier to read.

9. Practice: ArrayList in your application

Let’s make a to‑do list that you can add to and print:

import java.util.ArrayList;
import java.util.Scanner;

public class TodoApp 
{
    public static void main(String[] args) 
    {
        ArrayList<String> todo = new ArrayList<>();
        Scanner console = new Scanner(System.in);

        while (true) 
        {
            System.out.print("Enter a task (or an empty line to exit): ");
            String task = console.nextLine();
            if (task.isEmpty()) break;
            todo.add(task);
        }

        System.out.println("Your to-do list:");
        for (int i = 0; i < todo.size(); i++) 
        {
            System.out.println((i + 1) + ". " + todo.get(i));
        }
    }
}

I hope you liked our infinite array. It is the first of the Java collections you’ve met. I think you’ll like the others too.

1
Task
JAVA 25 SELF, level 12, lesson 1
Locked
Adding and retrieving an element
Adding and retrieving an element
1
Task
JAVA 25 SELF, level 12, lesson 1
Locked
Replace and remove elements
Replace and remove elements
1
Task
JAVA 25 SELF, level 12, lesson 1
Locked
Checking for an element in a list
Checking for an element in a list
1
Task
JAVA 25 SELF, level 12, lesson 1
Locked
To-Do List with User Input
To-Do List with User Input
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION