CodeGym /Courses /JAVA 25 SELF /List: ArrayList and LinkedList, basic operations

List: ArrayList and LinkedList, basic operations

JAVA 25 SELF
Level 26, Lesson 1
Available

1. Class ArrayList

In Java, the List interface is a contract: “I am an ordered collection of elements, and you can get an element by its number (index).”

Key properties of a List:

  • Elements are stored in a specific order (unlike a set).
  • You can store duplicate elements (for example: two times "John").
  • You can access an element by index: the first element has index 0, the second has 1, and so on.
  • You can add and remove elements at any position in the list.

The most popular implementation of the List interface is ArrayList. Under the hood it uses a regular array and automatically grows as data increases.

How to create an ArrayList?

import java.util.ArrayList;
import java.util.List;

public class Example {
    public static void main(String[] args) {
        // Create a list of strings
        List<String> students = new ArrayList<>();
    }
}

Explanation

  • List<String> is a variable of type “list of strings.” We declare the variable via the interface and create the object via a concrete class (ArrayList).
  • The angle brackets <String> specify the element type of the list (generics).

Main methods of ArrayList (and any List):

  • add(element) — add an element to the end of the list.
  • add(index, element) — insert an element at a specific index.
  • get(index) — get an element by index.
  • set(index, element) — replace an element at an index.
  • remove(index) — remove an element by index.
  • remove(Object) — remove the first element equal to the passed object.
  • size() — find out how many elements are in the list.

Example: Working with a list of students

import java.util.ArrayList;
import java.util.List;

public class StudentListDemo {
    public static void main(String[] args) {
        List<String> students = new ArrayList<>();

        // Add students
        students.add("John");
        students.add("Peter");
        students.add("Mary");

        // Print all students
        System.out.println("List of students: " + students);

        // Get the first student
        String first = students.get(0);
        System.out.println("First student: " + first);

        // Change the second student's name
        students.set(1, "Paul");
        System.out.println("After change: " + students);

        // Remove Mary
        students.remove("Mary");
        System.out.println("After removing Mary: " + students);

        // List size
        System.out.println("Total students: " + students.size());
    }
}

Result:

List of students: [John, Peter, Mary]
First student: John
After change: [John, Paul, Mary]
After removing Mary: [John, Paul]
Total students: 2

How does this relate to our application?
Suppose we have an app for tracking a student's tasks. Now we can store the task list as a List<String>, not as an array, and dynamically add new tasks.

2. Class LinkedList: when insertion and deletion speed matters

LinkedList is an alternative list implementation. It is built as a doubly linked chain: each node knows the previous and next elements. Like a train: inserting a “car” in the middle is fast and does not require rearranging the whole train.

Creating a LinkedList

import java.util.LinkedList;
import java.util.List;

public class Example {
    public static void main(String[] args) {
        List<String> tasks = new LinkedList<>();
    }
}

Features of LinkedList

  • Fast insertion and deletion at the beginning and in the middle of the list.
  • Slow access by index (to find the 100th element, you need to traverse the chain).
  • Good if you frequently add/remove elements not only at the end, but also at the beginning or in the middle.

Example: Using LinkedList

import java.util.LinkedList;
import java.util.List;

public class TaskListDemo {
    public static void main(String[] args) {
        List<String> tasks = new LinkedList<>();

        tasks.add("Wake up");
        tasks.add("Have breakfast");
        tasks.add("Go to classes");

        // Add a task to the beginning
        tasks.add(0, "Set an alarm");

        System.out.println("Task list: " + tasks);

        // Remove the first task (the earliest)
        tasks.remove(0);

        System.out.println("After removing the first task: " + tasks);
    }
}

3. Comparison of ArrayList and LinkedList

Criterion
ArrayList
LinkedList
Underlying structure Array Doubly linked list
Fast random access by index Yes (O(1)) No (O(n))
Fast insertion/deletion at the beginning/middle No (O(n)) Yes (O(1) — if you have a reference)
Fast insertion/deletion at the end Yes (usually O(1)) Yes (O(1))
Memory Consumes less memory More (extra references to neighbors)
Typical use cases Frequent index-based access Frequent insertions/deletions

Simple rule:

  • If you need fast access by index, use ArrayList.
  • If you frequently add/remove at the beginning or in the middle, use LinkedList.

4. Typical list operations

Iterating over list elements

Classic for loop

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

For-each loop (the most common way)

for (String name : students) {
    System.out.println("Name: " + name);
}

Lambda expression (Java 8+)

students.forEach(name -> System.out.println("Name: " + name));

Searching for elements

  • contains(element) — returns true if the element is in the list.
  • indexOf(element) — returns the index of the first occurrence of the element, or -1 if not found.
if (students.contains("John")) {
    System.out.println("John is in the list!");
}
int index = students.indexOf("John");
System.out.println("Index of John: " + index);

Clearing a list

clear() — removes all elements.

students.clear();
System.out.println("List after clearing: " + students);

5. When to use ArrayList and when LinkedList?

Think of it this way: ArrayList is good where you need fast index-based access and the list changes infrequently. For example, a long list of users or a message history — mostly reads.

LinkedList, on the other hand, is useful when you constantly insert or delete elements at the beginning/middle. This can be a queue, a stack, or an undo history.

In practice, ArrayList is used most of the time. And LinkedList remains a “just-in-case tool”: it sits in the toolbox, but sometimes it is exactly what you need.

6. Common mistakes when working with lists

Error #1: Out-of-bounds access. The most common situation is accessing a non-existent index. If the list has three elements and you write students.get(5), you will get an IndexOutOfBoundsException. Check size() before accessing.

Error #2: Removing an element during iteration. When iterating with for-each and removing elements at the same time, you will get a ConcurrentModificationException. For complex removals, use an index-based loop or an Iterator.

Error #3: Incorrect object comparison. If you store your own objects (for example, Student), the contains and remove methods rely on equals. If you do not override it, comparison will be by reference, not by content.

Error #4: Using raw types. Do not write List list = new ArrayList() — always specify the element type: List<String> list = new ArrayList<>(). Generics protect you from errors and make the code clearer.

1
Task
JAVA 25 SELF, level 26, lesson 1
Locked
Student Schedule 🗓️✍️
Student Schedule 🗓️✍️
1
Task
JAVA 25 SELF, level 26, lesson 1
Locked
My personal movie list "Watchlist" 🎬🍿
My personal movie list "Watchlist" 🎬🍿
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION