Han

Han Ferik

Home | Projects | AP CSA

AP CSA Unit 7: Using Objects

7.1:

ArrayLists are re-sizable lists that allow adding and removing items to change their size during run time.

The ArrayList class is in the java.util package. You must import java.util.ArrayList or java.util.* to use it.

An ArrayList object contains object references and is mutable, meaning it can change (by adding and removing items from it).

The ArrayList constructor ArrayList() constructs an empty list of size 0.

Java allows the generic type ArrayList<E>, where the generic type E specifies the type of the elements, like String or Integer. Without it, the type will be Object.

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

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

ArrayLists cannot hold primitive types like int or double, so you must use the wrapper classes Integer or Double to put numerical values into an ArrayList. However, autoboxing usually takes care of that for you.

Example:


// Import the ArrayList class
import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        // Create an ArrayList of Strings
        ArrayList names = new ArrayList<>();
        
        // Add elements
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");

        // Print the list
        System.out.println("Names: " + names);

        // Add an element at index 1
        names.add(1, "Diana");
        System.out.println("After adding Diana: " + names);

        // Remove an element
        names.remove("Charlie");
        System.out.println("After removing Charlie: " + names);

        // Access an element
        System.out.println("Element at index 1: " + names.get(1));
    }
}
  

7.2:

Example:


// Example demonstrating size, add, remove, and set methods
import java.util.ArrayList;

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

        // Adding elements
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);

        System.out.println("Initial List: " + numbers);
        System.out.println("Size: " + numbers.size());

        // Insert at index
        numbers.add(1, 15);
        System.out.println("After adding 15 at index 1: " + numbers);

        // Remove element at index 2
        int removed = numbers.remove(2);
        System.out.println("Removed element: " + removed);
        System.out.println("List after removal: " + numbers);

        // Replace element
        int oldValue = numbers.set(1, 25);
        System.out.println("Replaced " + oldValue + " with 25: " + numbers);
    }
}
  

7.3:

ArrayLists can be traversed with an enhanced for loop, a while loop, or a regular for loop using an index.

Deleting elements during a traversal of an ArrayList requires using special techniques to avoid skipping elements, since remove moves all the elements above the removed index down.

Since the indices for an ArrayList start at 0 and end at the number of elements − 1, accessing an index value outside of this range will result in an IndexOutOfBoundsException being thrown.

Changing the size of an ArrayList while traversing it using an enhanced for loop can result in a ConcurrentModificationException being thrown. Therefore, when using an enhanced for loop to traverse an ArrayList, you should not add or remove elements.

Example:


// Traversing and removing elements safely
import java.util.ArrayList;

public class ArrayListTraversalExample {
    public static void main(String[] args) {
        ArrayList numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        numbers.add(40);

        // Using a regular for loop to remove even numbers
        for (int i = 0; i < numbers.size(); i++) {
            if (numbers.get(i) % 20 == 0) {
                numbers.remove(i);
                i--; // Adjust index after removal
            }
        }
        System.out.println("After removing even numbers: " + numbers);
    }
}
  

7.5:

Sequential/linear search algorithms check each element in order until the desired value is found or all elements in the array or ArrayList have been checked.

The binary search algorithm starts at the middle of a sorted array or ArrayList and eliminates half of the array or ArrayList in each iteration until the desired value is found or all elements have been eliminated.

Data must be in sorted order to use the binary search algorithm. This algorithm will be covered more in Unit 10.

Informal run-time comparisons of program code segments can be made using statement execution counts.

Example:


// Linear and Binary Search
import java.util.ArrayList;
import java.util.Collections;

public class SearchExample {
    public static void main(String[] args) {
        ArrayList numbers = new ArrayList<>();
        Collections.addAll(numbers, 1, 3, 5, 7, 9, 11);

        // Linear Search
        int target = 7;
        boolean found = false;
        for (int num : numbers) {
            if (num == target) {
                found = true;
                break;
            }
        }
        System.out.println("Linear Search: Target " + target + " found? " + found);

        // Binary Search
        int index = Collections.binarySearch(numbers, target);
        System.out.println("Binary Search: Target " + target + " found at index: " + index);
    }
}
  

7.6:

Selection sort and insertion sort are iterative sorting algorithms that can be used to sort elements in an array or ArrayList.

Informal run-time comparisons of program code segments can be made using statement execution counts.

Example:


// Selection Sort
import java.util.ArrayList;

public class SelectionSortExample {
    public static void main(String[] args) {
        ArrayList numbers = new ArrayList<>();
        numbers.add(40);
        numbers.add(10);
        numbers.add(30);
        numbers.add(20);

        for (int i = 0; i < numbers.size() - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < numbers.size(); j++) {
                if (numbers.get(j) < numbers.get(minIndex)) {
                    minIndex = j;
                }
            }
            // Swap
            int temp = numbers.get(i);
            numbers.set(i, numbers.get(minIndex));
            numbers.set(minIndex, temp);
        }
        System.out.println("Sorted List: " + numbers);
    }
}
  

Find me on the interwebs!

Github LinkedIn Instagram Facebook