ArrayLists in Java

Limitations of Arrays

  • Arrays have a fixed size, which can be a limitation when the required size is unknown or changes during program execution.

  • Arrays provide only low-level access using get and set methods.

Introduction to ArrayLists

  • ArrayLists are dynamic arrays that automatically resize as needed.

  • They offer additional helpful methods beyond basic get and set.

Creating ArrayLists

  • Import the ArrayList class from the java.util package:

    • import java.util.*; (imports all classes in the package)

    • import java.util.ArrayList; (imports only the ArrayList class)

  • Declare an empty ArrayList of a specific type using angle brackets:

    • ArrayList<String> list = new ArrayList<String>(); (creates an ArrayList to store strings)

    • The type within the angle brackets specifies the type of elements the ArrayList will hold.

Templatized Types

  • ArrayLists require specifying the type they will store using angle brackets (e.g., <String>, <Integer>).

  • To store primitive types, use the corresponding wrapper classes:

    • Integer for int

    • Double for double

Auto-boxing and Unboxing

  • Java automatically handles the conversion between primitive types and their corresponding wrapper objects.

    • Auto-boxing: Converting a primitive type to its wrapper object (e.g., int to Integer).

    • Unboxing: Converting a wrapper object to its primitive type (e.g., Integer to int).

Adding Elements to an ArrayList

  • Use the add method to append elements to the end of the list:

    • list.add(5);

    • list.add(3);

    • list.add(10);

    • list.add(4);

Getting Values from an ArrayList

  • Use the get method to retrieve a value at a specific index:

    • int val = list.get(1); (retrieves the value at index 1, which is 3 in this case)

Setting Values in an ArrayList

  • Use the set method to change a value at a specific index:

    • list.set(2, 88); (sets the value at index 2 to 88)

Getting the Size of an ArrayList

  • Use the size method to determine the number of elements in the ArrayList:

    • list.size() (returns the number of elements in the list)

    • Important Difference: size() returns the number of elements in the list, while for arrays, length is a property denoting the fixed size of an array.

Looping Over an ArrayList

  • Standard for loop:

    • java for (int i = 0; i < list.size(); i++) { int element = list.get(i); // Use element }

  • Enhanced for loop (for-each loop):

    • java for (int elm : list) { // Use elm }

    • The enhanced for loop iterates through each element in the list, assigning the element to the variable elm.

Quick Reference of ArrayList Methods

  • size(): Returns the number of elements in the list (an int).

  • add(E elem): Adds the element elem to the end of the list. E represents the templatized type of the ArrayList.

  • E get(int index): Returns the element at the specified index. E represents the templatized type of the ArrayList.

  • remove(int index): Removes the element at the specified index and shifts subsequent elements.

  • add(int index, E element): Inserts the element at the specified index and shifts subsequent elements.

ArrayList and the List Interface

  • The ArrayList class implements the List interface.

  • This allows for using the List interface type on the left-hand side of a declaration:

    • List<String> myList = new ArrayList<String>();

  • Other classes can also implement the List interface, but the focus here is on ArrayList.

ArrayList Examples

  • Creating an ArrayList of Strings:

    • ArrayList<String> myList = new ArrayList<String>();

    • myList.add("Hello");

    • myList.add("World");

    • Printing elements:

      • System.out.println(myList.get(0)); (prints "Hello")

      • System.out.println(myList.get(1)); (prints "World")

  • Using ArrayList with primitive types (Integer):

    • ArrayList<Integer> myList = new ArrayList<Integer>();

    • myList.add(100);

    • myList.add(200);

    • Java handles the auto-boxing of int to Integer.

  • Using the size method:

    • java ArrayList<Integer> numbers = new ArrayList<Integer>(); for (int i = 0; i < 100; i++) { numbers.add(i); } System.out.println(numbers.size()); // Prints 100

  • Simulating a reading list (ArrayList of Strings):

    • Demonstrates various add and remove methods.

    • Also shows indexOf usage.

ArrayList as an Instance Variable

  • Example: Simulating a cell phone with a list of text messages.

  • It contains the classes: TextMessage and CellPhone

  • TextMessage Class:

    • Attributes: message (String), sender (String), receiver (String).

    \begin{array}{ll}
    \text{message} & \text{The content of the text message} \\
    \text{sender} & \text{The sender of the text message} \\
    \text{receiver} & \text{The receiver of the text message}
    \end{array}
    
    • Constructor to initialize these attributes.

    • toString method to represent the message.

  • CellPhone Class:

    • Attribute: ArrayList<TextMessage> texts to store text messages.

    • Constructor initializes the ArrayList.

    • addText(TextMessage text) method adds a text message to the list.

    • getTextMessages() method returns the list of text messages.