ArrayList Methods

🙋 Need help? Ask an expert now!

The index of an ArrayList starts at 0 and it cannot equal the size of the ArrayList, just like we mentioned with strings and arrays. ArrayList is a class, which means it has its own methods like the String class does. Take a look at the commonly used methods in the ArrayList class and their functions.
package exlcode;

import java.util.ArrayList;

public class ArrayListMethodExample {

  public static ArrayList exampleVariableOne = new ArrayList();

  public static void main(String[] args) {
    // adds "Hello" to the ArrayList
    // adds "World" to the 0th index of the ArrayList
    exampleVariableOne.add(0, "World");
    // removes "Hello" from the ArrayList
    // changes "World" to "Java"
    exampleVariableOne.set(0, "Java");
    // access the first element of the ArrayList
    // prints the size of the ArrayList

These are the important methods to learn for an ArrayList:

  1. add(value) or add(index,value)

    Adds an element to the end of an ArrayList. The method returns "true" if it is treated as a boolean value. When you add a specific index as a parameter, it will add the value at the specified index and move everything else after it up by one index.

  2. remove(index)

    Removes an element from the ArrayList. It can return a reference to the deleted element if it is called. The method will shift the other elements down an index to account for the deleted element.

  3. set(index, value)

    Combines add() and remove() by replacing the value at "index" with the new "value"

  4. get(index)

    Accesses the element at a particular index.

  5. size()

    Returns the current length of the ArrayList. This method is important as the size may change when using the methods above.

Edit Me on GitHub!

Application Question

Consider the following code segment:

ArrayList<String> varOne = new ArrayList<String>();
            varOne.set(2, "HTML");
            varOne.add(1, "JavaScript");

What is printed as a result of executing the code segment?