Skip to the content.
Home 7.1 Introduction 7.2 Methods 7.3 Traversing 7.4 Algorithms 7.5 Searching 7.6 Sorting 7.7 Ethical Issues

7.4 - Developing Algorithms Using ArrayLists

ArrayLists Lesson

AP CSA

7.4 Developing Algorithms Using ArrayLists

Common Arraylist Methods:

  • size(): Returns the size of the arraylist as an Integer
  • add(object): Adds an object to the end of your ArrayList
  • void add(index, object): Addes an object to an index of your choice. Shifts the index of everything to the right by one and increases size by 1
  • get(index): Retrieves the object at the index specified
  • set(index, obj): Like void add, but instead of adding, it replaces the object that’s already in that index
  • remove(index): Removes the object at specified index
//size() & add(object)

ArrayList<Double> numbers = new ArrayList<>();
    numbers.add(1.0);
    numbers.add(2.0);
    numbers.add(3.0);

int size = numbers.size();

System.out.println(size);
3
//void add(index, object)
//get(index)
ArrayList<Double> numbers = new ArrayList<>();
    numbers.add(1.0);
    numbers.add(2.0);
    numbers.add(3.0);

System.out.println(numbers.get(2));

    numbers.add(2,4.0);

System.out.println(numbers.get(2));
System.out.println(numbers.get(3));
3.0
4.0
3.0
// set(index, obj)


ArrayList<Double> numbers = new ArrayList<>();
    numbers.add(1.0);
    numbers.add(2.0);
    numbers.add(3.0);

System.out.println(numbers.get(2));

    numbers.set(2,4.0);

System.out.println(numbers.get(2));
System.out.println(numbers.get(3));

3.0
4.0



---------------------------------------------------------------------------

java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3

	at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)

	at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)

	at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)

	at java.base/java.util.Objects.checkIndex(Objects.java:359)

	at java.base/java.util.ArrayList.get(ArrayList.java:427)

	at .(#40:1)
// remove(index)


ArrayList<Double> numbers = new ArrayList<>();
    numbers.add(1.0);
    numbers.add(2.0);
    numbers.add(3.0);
System.out.println(numbers.get(2));
    numbers.remove(2);

System.out.println(numbers.get(0));
System.out.println(numbers.get(1));
System.out.println(numbers.get(2));

//anybody know why we get an IndexOutofBoundsException eror?
3.0
1.0
2.0



---------------------------------------------------------------------------

java.lang.IndexOutOfBoundsException: Index 2 out of bounds for length 2

	at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)

	at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)

	at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)

	at java.base/java.util.Objects.checkIndex(Objects.java:359)

	at java.base/java.util.ArrayList.get(ArrayList.java:427)

	at .(#27:1)

Here’s an example of a program using Arrays that finds the maximum value:

public class Main {
    public static void main(String[] args) {
        double[] values = {1, 2, 3, 4, 5};

        double maxValue = findMax(values);
        System.out.println("The maximum value is: " + maxValue);
    }

    private static double findMax(double[] values) {
        double max = values[0];
        for (int index = 1; index < values.length; index++) {
            if (values[index] > max) {
                max = values[index];
            }
        }
        return max;
    }
}
Main.main(null);
The maximum value is: 5.0

Now, how can we modify this to use an ArrayList?


public class Main {
    public static void main(String[] args) {
        ArrayList<Double> values = new ArrayList<>();
        values.add(1.2);
        values.add(3.4);
        values.add(2.6);
        values.add(4.9);
        values.add(0.8);

        double maxValue = findMax(values);
        System.out.println("The maximum value is: " + maxValue);
    }

    private static double findMax(ArrayList<Double> values) {
        double max = values.get(0);

        for (int index = 1; index < values.size(); index++) {
            if (values.get(index) > max) {
                max = values.get(index);
            }
        }
        return max; 
    }
}
Main.main(null);

The maximum value is: 4.9

Homework:

(Paragraph Answer)

  1. What is the difference between the two examples above. Which one is better and why?

The two code examples do the same thing—finding the highest number in a list—but they use different ways to store the numbers. The first example uses a fixed-size array (double[] values), where numbers are set directly and accessed by their position. This usually makes it faster. The second example uses an ArrayList, which can change size and allows you to add numbers with the add() method, but it accesses numbers with the get() method, which is a bit slower. Also, the first example uses the basic type double, which saves memory, while the second one uses the Double class, which can slow things down a bit due to extra steps. In the end, which one to use depends on what you need for your application.

(Code Answer)

  1. Make your own algorithm using ArrayLists that finds the sum of the elements in the ArrayList
import java.util.ArrayList;

public class ArrayListSum {
    public static void main(String[] args) {
        // Create an ArrayList and add some elements
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        numbers.add(40);
        numbers.add(50);

        // Calculate the sum of the elements
        int sum = sumArrayList(numbers);

        // Print the result
        System.out.println("The sum of the elements is: " + sum);
    }

    public static int sumArrayList(ArrayList<Integer> list) {
        int sum = 0; // Initialize sum variable
        for (Integer number : list) { // Iterate through each element in the ArrayList
            sum += number; // Add each element to the sum
        }
        return sum; // Return the total sum
    }
}