CodeGym /Java Course /Module 1. Java Syntax /Collections in Java: ArrayList

Collections in Java: ArrayList

Module 1. Java Syntax
Level 16 , Lesson 2
Available

1. ArrayList class

Today we will explore the ArrayList class. This is the first of several classes known as collections. In Java, collections are such a broad and useful topic that an entire CodeGym quest is devoted to them.

To fully understand how collections are structured and all their nuances, you need to first learn OOP, interfaces, inheritance, the basics of multithreading, and much more.

So today we'll just get acquainted with the simplest kind of collection. But at a deep enough level so that you understand how to use it and how it works. Now then, meet the ArrayList collection.

The backstory

I'll start with a little background. Programmers really didn't like one aspect of arrays: the fact that their size cannot be changed. What if you need to store three more elements in an array, but there is only one empty cell?

The only solution to the space limitations of an array was to create a very large array in order to accommodate all the elements you might need to store. But this was usually a waste of memory. If an array usually contained two or three elements but there was even a tiny chance that it would need to store 100 of them, then it was necessary to create an array with the capacity to store 100.

So what did programmers come up with? They wrote the ArrayList class, which did the same work as the Array class, but was resizable.

ArrayList class

The name of the ArrayList class is formed from two words: Array + List. Array is an array and List is a list.

Each ArrayList object contains an ordinary array of elements. When you read elements from an ArrayList, the object retrieves them from its internal array. When you write elements, it writes them to the internal array.

The ArrayList class lacks all the disadvantages that arrays have. It knows how to:

  • Store elements of a specific type
  • Dynamically resize the list
  • Add elements to the end of the list
  • Insert elements at the beginning or middle of the list
  • Remove elements from anywhere in the list

For more details, see below:


2. Creating an ArrayList object

To create an ArrayList object, you need to write code like this:

ArrayList<TypeParameter> name = new ArrayList<TypeParameter>();

Where ArrayList is the collection type/class, TypeParameter is the type of the elements stored in the ArrayList collection, and name is the name of an ArrayList<TypeParameter> variable.

The name variable has a generic type. It consists of two types: the type of the collection is indicated first, and then angle brackets are used to indicate the type of the elements stored in the collection.

Examples:

Code Description
ArrayList<Integer> list = new ArrayList<Integer>();
List of integers
ArrayList<String> list = new ArrayList<String>();
List of strings
ArrayList<Double> list = new ArrayList<Double>();
List of real numbers

Unlike arrays, collections cannot store primitive types, only reference types. So if you need a collection of ints, use the Integer wrapper class instead.


3. Operations with an ArrayList

Initially, the length of the newly created list is zero, since it contains 0 elements. If you add one element to the list, its length increases by 1. If you remove the added element, the length decreases back to zero.

The following table can teach you more about the methods of the ArrayList class:

Methods Description
void add(Type value)
Adds the passed element to the list
void add(int index, Type value)
Adds an element to a specific location in the list.
Type get(int index)
Returns the element whose index is index
void set(int index, Type value)
Assigns value to the element whose index is index
Type remove(int index)
Removes the element whose index is index. Returns the removed element.
Type remove(Type value)
Removes the element that you pass to the method. If there is more than one such element, the first one will be removed.
void clear()
Clears the list, i.e. removes all elements from the list.
boolean contains(Type value)
Checks whether the list contains value.
boolean isEmpty()
Checks whether the list is empty or not. In other words, whether the length of the list is zero.
int size()
Returns the size of the list, i.e. the number of elements in the list.
Type[] toArray(Type[] array)
Returns an array containing the elements of the list.
You need to pass the array to the method.

These methods let you do almost anything you might want to with the list: swap elements, add elements, and remove elements. You can clear the list with a single command, or even convert the list to an array.



4. Comparison of ArrayList and Array

I don't think we can avoid comparing ArrayList and an array.

There are only 4 actions you can perform with arrays:

  • Create an array
  • Get an element by index
  • Set an element by index
  • Get the length of the array

Here are these operations as they apply to an array and an ArrayList:

Array ArrayList
String[] array = new String[10];
ArrayList<String> list = new  ArrayList<String>();
String s = array[0];
String s = list.get(0);
array[0] = "Bye";
list.set(0, "Bye");
int count = array.length;
int count = list.size();

Let's compare how an ArrayList works versus how an array works. For example, let's implement this task: "read 10 strings from the keyboard and display them on the screen in reverse order"

Using Array Using ArrayList
Scanner console = new Scanner(System.in);

// Read strings from the keyboard
String[] list = new String[10];

for (int i = 0; i < list.length; i++)
{
    String s = console.nextLine();
    list[i] = s;
}

// Display the contents of the array on the screen
for (int i = 0; i < list.length; i++)
{
    int j = list.length - i - 1;
    System.out.println(list[j]);
}
Scanner console = new Scanner(System.in);

// Read strings from the keyboard
ArrayList<String> list = new ArrayList<String>();

for (int i = 0; i < 10; i++)
{
    String s = console.nextLine();
    list.add(s);
}

// Display the contents of the collection on the screen
for (int i = 0; i < list.size(); i++)
{
    int j = list.size() - i - 1;
    System.out.println(list.get(j));
}

The analogy is clear. Everything is somehow shorter and clearer for arrays. But ArrayList isn't difficult either: to get an element, we use the get() method; to change an element, the set() method; to get the length of the list, the size() method.

So why do programmers use the ArrayList class?

The whole point, of course, is all the other methods that ordinary arrays don't have:

  • Add an element to the list
  • Add an element to the middle of the list
  • Find an element in the list
  • Removing an element from a list

Comments (4)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Pekotski Level 16, Zurich, Switzerland
19 February 2024
Here are 2 videos that explain bubble sort in details: https://www.youtube.com/watch?v=uJLwnsLn0_Q & https://www.youtube.com/watch?v=g8qeaEd2jTc There is a cosmetic difference between the two, but I think wrapping the brain around it, teaches understanding of nested loops.
Campbell, Jackson Level 12, Corona, USA
11 December 2023
actually light y'all
Shanthi Sri Level 64, CodeGym University in India, India Expert
28 September 2023
correct in this task is hard
thompson, braedyn Level 22, United States of America, USA
21 September 2023
hard