Post

Created by @nathanedwards
 at October 31st 2023, 4:41:09 pm.

AP Computer Science Exam Question

import java.util.ArrayList;

public class ArrayListIntro {

    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<Integer>();

        // Add elements to the ArrayList
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        numbers.add(40);

        // Remove an element from the ArrayList
        numbers.remove(2);

        // Access an element at a specific index
        int element = numbers.get(1);

        // Calculate the size of the ArrayList
        int size = numbers.size();

        // Print the elements in the ArrayList
        for (int i = 0; i < numbers.size(); i++) {
            System.out.println(numbers.get(i));
        }
    }
}

Consider the above code snippet.

  1. What is the output of the code?

A) 10 20 40

B) 10 20 30 40

C) 10 30 40

D) 20 30 40

  1. Explain the purpose and usage of the ArrayList class along with the relevant methods used in the code snippet.

Answer

  1. The output of the code is:

    B) 10 20 30 40

    Explanation: The code first creates an ArrayList called numbers to store integers. Four elements (10, 20, 30, and 40) are added to the numbers ArrayList using the add() method. Then, the element at index 2 (30) is removed using the remove() method. Next, the element at index 1 (20) is accessed using the get() method and stored in the variable element. The size of the numbers ArrayList is calculated using the size() method and stored in the variable size. Finally, the elements in the numbers ArrayList are printed using a for loop.

  2. The ArrayList class in Java is a resizable array implementation of the List interface. It provides dynamic resizing, which means the size of the ArrayList can grow or shrink at runtime based on the number of elements added or removed.

In the given code snippet, the ArrayList is used to store integers. Here are the methods used in the code:

  • add(element): Appends the specified element to the end of the ArrayList.
  • remove(index): Removes the element at the specified index from the ArrayList.
  • get(index): Returns the element at the specified index in the ArrayList.
  • size(): Returns the number of elements in the ArrayList.

These methods are used to add elements to the ArrayList, remove an element, access an element at a specific index, and calculate the size of the ArrayList.