Unit 7 Lesson 1 - ArrayList

LESSON 1 Summary of ArrayLists in Java

This lesson covers ArrayLists, a dynamic collection in Java that only stores objects (class data types) rather than primitive types. Unlike arrays, which have a fixed size, ArrayLists are mutable, meaning their size can change as elements are added or removed. They also include built-in methods that simplify common operations like inserting, deleting, and retrieving elements.

Key Concepts

1. Memory Storage
  • Primitive types (e.g., int, double, boolean, char) store values directly in memory.

  • Class data types store references to memory locations where the actual data is held.

  • Since an ArrayList only stores objects, it holds references to elements rather than storing the elements directly.

2. Advantages of ArrayLists
  • Dynamic Sizing: Unlike arrays, ArrayLists can grow or shrink as needed without data loss.

  • Built-in Methods: The ArrayList class provides useful methods for modifying lists, such as adding, removing, and sorting elements.

3. Declaring and Initializing an ArrayList
  • Import the Class:

    import java.util.ArrayList;
  • Creating an Empty ArrayList:

    ArrayList<DataType> list = new ArrayList<DataType>();
  • Creating an ArrayList with a Set Capacity:


    ArrayList<DataType> list = new ArrayList<DataType>(10);
  • Specifying Data Type:

    • Use alligator brackets < > to define the type of elements stored in the list.

    • Example for String elements:


      ArrayList<String> list = new ArrayList<String>();
4. Essential ArrayList Methods for AP Exam

Method

Description

list.add(e);

Adds e to the end of the list

list.add(i, e);

Inserts e at index i (shifts elements right)

list.set(i, e);

Replaces the element at index i with e

list.get(i);

Retrieves the element at index i

list.remove(i);

Removes and returns the element at index i (shifts elements left)

list.size();

Returns the total number of elements in the list

  • Indexing starts at 0, just like arrays.

  • Using an invalid index results in an IndexOutOfBoundsException, except for add(), which allows adding at index size().

5. Using Wrapper Classes for Primitives

Since ArrayLists only store objects, primitive types like int or double cannot be directly stored. Instead, Java provides wrapper classes (e.g., Integer, Double, Boolean) to convert primitives into objects through autoboxing (automatic conversion) and unboxing (retrieving primitive values).

Example:

ArrayList<Integer> list = new ArrayList<Integer>();
list.add(2);
list.add(5);
list.add(0);
System.out.println(list); // Output: [2, 5, 0]

Conclusion

ArrayLists provide a flexible and efficient alternative to arrays in Java. Their dynamic resizing and built-in methods make them a powerful tool for handling collections of objects, especially when working with unknown or changing data sizes. However, developers must be careful with indexing to avoid errors.

robot