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.
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.
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.
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>();
Method | Description |
---|---|
| Adds |
| Inserts |
| Replaces the element at index |
| Retrieves the element at index |
| Removes and returns the element at index |
| 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()
.
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]
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.