ArrayList in Java


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.


Introduction

In this lesson, we will explore the ArrayList class in Java, a part of the Java Collections Framework. The ArrayList is a resizable array, which can grow as needed to accommodate new elements. This flexibility makes it a powerful tool for managing collections of data where the size may change dynamically.

Understanding how to use ArrayList is crucial for any Java programmer, as it is commonly used in various applications, from simple programs to complex enterprise-level systems.

Understanding the Basics

The ArrayList class is part of the java.util package and implements the List interface. Unlike arrays, which have a fixed size, an ArrayList can dynamically resize itself when elements are added or removed.

Here is a simple example to illustrate the basic usage of ArrayList:

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

public class Main {
    public static void main(String[] args) {
        // Creating an ArrayList of Strings
        List<String> fruits = new ArrayList<>();
        
        // Adding elements to the ArrayList
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        
        // Printing the ArrayList
        System.out.println(fruits);
    }
}

In this example, we create an ArrayList of String type, add three elements to it, and print the list.

Main Concepts

Let's delve deeper into some key concepts and techniques related to ArrayList:

  • Adding Elements: Use the add() method to add elements to the ArrayList.
  • Accessing Elements: Use the get() method to access elements at a specific index.
  • Removing Elements: Use the remove() method to remove elements from the ArrayList.
  • Size of the List: Use the size() method to get the number of elements in the ArrayList.

Here is an example demonstrating these concepts:

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

public class Main {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        
        // Accessing elements
        System.out.println("First fruit: " + fruits.get(0));
        
        // Removing an element
        fruits.remove("Banana");
        
        // Size of the list
        System.out.println("Number of fruits: " + fruits.size());
    }
}

Examples and Use Cases

Let's look at some practical examples and use cases for ArrayList:

Example 1: Managing a To-Do List

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

public class ToDoList {
    public static void main(String[] args) {
        List<String> tasks = new ArrayList<>();
        tasks.add("Buy groceries");
        tasks.add("Clean the house");
        tasks.add("Pay bills");
        
        System.out.println("To-Do List: " + tasks);
        
        // Marking a task as done
        tasks.remove("Clean the house");
        System.out.println("Updated To-Do List: " + tasks);
    }
}

Example 2: Storing Student Names

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

public class StudentNames {
    public static void main(String[] args) {
        List<String> students = new ArrayList<>();
        students.add("John");
        students.add("Jane");
        students.add("Jack");
        
        System.out.println("Student Names: " + students);
        
        // Adding a new student
        students.add("Jill");
        System.out.println("Updated Student Names: " + students);
    }
}

Common Pitfalls and Best Practices

When working with ArrayList, there are some common pitfalls to avoid and best practices to follow:

  • Avoiding ConcurrentModificationException: Be cautious when modifying an ArrayList while iterating over it. Use an Iterator to safely remove elements.
  • Initial Capacity: If you know the approximate number of elements, set an initial capacity to improve performance.
  • Type Safety: Always specify the type of elements in the ArrayList to avoid ClassCastException.

Advanced Techniques

For more advanced usage, you can explore the following techniques:

  • Sorting: Use Collections.sort() to sort the elements in an ArrayList.
  • Synchronization: Use Collections.synchronizedList() to create a synchronized ArrayList for thread-safe operations.

Here is an example of sorting an ArrayList:

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

public class SortArrayList {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Banana");
        fruits.add("Apple");
        fruits.add("Cherry");
        
        // Sorting the ArrayList
        Collections.sort(fruits);
        System.out.println("Sorted Fruits: " + fruits);
    }
}

Code Implementation

Here is a comprehensive example that demonstrates the correct use of ArrayList:

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

public class ArrayListExample {
    public static void main(String[] args) {
        // Creating an ArrayList of Strings
        List<String> fruits = new ArrayList<>();
        
        // Adding elements to the ArrayList
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        
        // Accessing elements
        System.out.println("First fruit: " + fruits.get(0));
        
        // Removing an element
        fruits.remove("Banana");
        
        // Size of the list
        System.out.println("Number of fruits: " + fruits.size());
        
        // Sorting the ArrayList
        Collections.sort(fruits);
        System.out.println("Sorted Fruits: " + fruits);
    }
}

Debugging and Testing

When debugging and testing code involving ArrayList, consider the following tips:

  • Print Statements: Use print statements to check the contents of the ArrayList at various stages.
  • Unit Tests: Write unit tests to verify the behavior of methods that manipulate the ArrayList.

Here is an example of a simple unit test for an ArrayList:

import org.junit.Test;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;

public class ArrayListTest {
    @Test
    public void testAddElement() {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        assertEquals(1, fruits.size());
        assertEquals("Apple", fruits.get(0));
    }
}

Thinking and Problem-Solving Tips

When working with ArrayList, consider the following strategies:

  • Break Down Problems: Divide complex problems into smaller tasks that can be solved using ArrayList.
  • Practice: Regularly practice coding problems involving ArrayList to improve your skills.

Conclusion

In this lesson, we covered the basics and advanced concepts of ArrayList in Java. We explored how to create, manipulate, and optimize ArrayList for various use cases. Mastering ArrayList is essential for efficient data management in Java applications.

Keep practicing and exploring further applications of ArrayList to enhance your programming skills.

Additional Resources

For further reading and practice, consider the following resources: