7.2: ArrayList Methods

Learning Objectives

Students will be able to represent collections of related object reference data using ArrayList objects.

Essential Knowledge

  • Iteration statements provide a means to access all the elements stored within an ArrayList. This process is referred to as “traversing the ArrayList.”

  • The following ArrayList methods, including what they do and when they are used, are part of the Java Quick Reference:

    • int size() - Returns the count of elements within the list.
    • boolean add(E obj) - Appends the object obj to the end of the list and returns true.
    • void add(int index, E obj) - Inserts obj at the specified index, shifting elements at and above that position to the right (incrementing their indices by 1) and increasing the list’s size by 1.
    • E get(int index) - Retrieves the element at the given index in the list.
    • E set(int index, E obj) - Replaces the element at the specified index with obj and returns the previous element at that index.
    • E remove(int index) - Deletes the element at the specified index, shifting all subsequent elements one index to the left, reducing the list’s size by one, and returning the removed element.
  • Java allows the generic ArrayList<E>, where the generic type E specifies the type of element.

  • When ArrayList<E> is specified, the types of the reference parameters and return type when using the methods are type E.

  • ArrayList<E> is preferred over ArrayList because it allows the compiler to find errors that would otherwise be found at runtime.

Size of the ArrayList

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

Consider the following code:

ArrayList<Integer> a1 = new ArrayList<>();
System.out.println(a1.size());
0

Adding Items to an ArrayList

  • boolean add(E obj); : Appends obj to the end of the list and returns true.
  • void add(int index, E obj) : Inserts obj at position index, as long as index is within the list’s length. It moves each element in the list 1 index higher and adds 1 to the list’s size.

Consider the following code:

ArrayList<Double> a2 = new ArrayList<>();
a2.add(1.0);
a2.add(2.0);
a2.add(3.0);
a2.add(1, 4.0);
System.out.println(a2);
[1.0, 4.0, 2.0, 3.0]

Let’s Look at an Example

Consider the following code:

ArrayList<String> h = new ArrayList<>();

h.add("Hello");
h.add("Hello");
h.add("HeLLO");
h.add("Hello");
h.add(1, "Hola");

h.add(26.2);
h.add(new String("Hello"));
h.add(false);
|   h.add(26.2);

incompatible types: double cannot be converted to java.lang.String

Now, consider this code:

ArrayList<String> g = new ArrayList<>();

g.add("Hello");
g.add("Hello");
g.add("HeLLO");
g.add("Hello");
g.add(1, "Hola");

g.add(new String("Hello"));

System.out.println(g);
[Hello, Hola, Hello, HeLLO, Hello, Hello]

Question: Why does this code work?

It doesn’t work because a number defines h and for it to work a string for example must define g.

Deleting Items from an ArrayList

E remove(int index) : Removes the element at position index, and moves the elements at position index + 1 and higher to the left. It also subtracts one from the list’s size. The return value is the element formerly at position index.

// If you are confused of what list g is, look back at the previous code.
g.remove(3);
String former = g.remove(0);
System.out.println(former);
Hello

Updating Items in an ArrayList

To update variables or object properties in Java, simply assign new values using the = operator or update object fields through methods. Make sure the data types match and understand how scopes affect where updates can occur.

String car = g.set(1, "xx");
System.out.println(car);
System.out.println(g);
Hello


[Hola, xx, Hello, Hello]

Accessing Items in an ArrayList

In Java, you can access items in an array by using the index of the element, with array indices starting from 0. For example, array[0] will access the first element, and array[2] will access the third element. You can use a loop, such as a for or while loop, to iterate through all the elements of the array.

String hello = g.get(3);
System.out.println(hello);
System.out.println(g);
Hello
[Hola, xx, Hello, Hello]

Passing an ArrayList as a Method Parameter

The only time that it is wise to use ArrayList instead of ArrayList<E> is when it is as a function parameter and it is only using ArrayList<>.get(E) or ArrayList<>.size(). Consider the following code:

private void accessOnly(ArrayList arr) {
    if (arr.size() > 0) {
        System.out.println(arr.get(0)); // Change the index to the one you want to access
    } else {
        System.out.println("Array is empty");
    }
}

ArrayList<Integer> myList = new ArrayList<Integer>();
accessOnly(myList);
Array is empty

Returning an ArrayList from a Method

In order for you to return an ArrayList, the data type must be specified, and the return type must be the same as the return value. Consider the following code:

private ArrayList<String> returnTheSame() {
    ArrayList<String> arr = new ArrayList<String>(); // Initialize the ArrayList
    arr.add("Hello");
    return arr;
}

ArrayList<String> result = returnTheSame();
System.out.println(result);

[Hello]

Hacks

  • The learning objective is that “Students will be able to represent collections of related object reference data using ArrayList objects.” What does this mean to you?

  • Answer the following questions:

    • Look back at Size of the ArrayList. What does the code output and why?
    • 0 because there are 0 items in the array list
    • Look back at Adding items to an ArrayList. What does the code output and why? What type of function is void, and what will be the return value?
    • the add() method is a void method which doesnt return anything and simply adds stuff to the array
    • Look back at Example 1. What two lines did we remove? Why?
    • If an ArrayList is being used as a parameter, what are the only two methods I can use from it? What would happen if I tried to use any other methods?
  • Using the Hack Helper, write code that will:

    • Add 2 items to the list.
    • Remove an item from the list anywhere of the user’s choice.
    • Replace am item anywhere in the list of the user’s choice.
    • Get the first and last element of the list, no matter the length.
    • Return the items added, removed, replaced, and the list’s size, in one string.

Hack Helper

public class ArrayListMethodsExample {
    private ArrayList<Integer> manipulateList(int removeIndex, int replaceIndex, int replaceValue) {
        ArrayList<Integer> arr = new ArrayList<Integer>();
        
        arr.add(10);
        arr.add(20);

        int addedItem1 = 10;
        int addedItem2 = 20;

        int removedItem = arr.remove(removeIndex);

        int replacedItem = arr.set(replaceIndex, replaceValue);

        int firstElement = arr.get(0);
        int lastElement = arr.get(arr.size() - 1);

        String result = "Added: " + addedItem1 + ", " + addedItem2 +
                        "\nRemoved: " + removedItem +
                        "\nReplaced: " + replacedItem + " with " + replaceValue +
                        "\nFirst Element: " + firstElement +
                        "\nLast Element: " + lastElement +
                        "\nFinal Size: " + arr.size();
        
        System.out.println(result);
        
        return arr;
    }

    public static void main(String[] args) {
        ArrayListMethodsExample example = new ArrayListMethodsExample();
        
    }
}