7.4 Developing Algorithms Using ArrayLists

Prerequisite Knowledge:

  • 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

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

public class ArrayListExample {
    private 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;
    }
    
    public static void main(String[] args) {
        double[] nums = {1.0, 3.0, 2.0, 2.0, 1.0, 5.0, 2.421, 4.0, 61.0, 2.0, 51.0, 120.0};
        ArrayListExample example = new ArrayListExample();
        double max = example.findMax(nums);
        System.out.println("Maximum value: " + max);
    }
}

ArrayListExample.main(null);

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

public class ArrayListExample {
    private 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;
    }
    
    public static void main(String[] args) {
        ArrayList<Double> nums = new ArrayList<>();
        nums.add(41.0);
        nums.add(384.0);
        nums.add(2.0);
        nums.add(25.0);
        nums.add(11.0);
        nums.add(120.0);
        nums.add(21.0);
        nums.add(4.03);
        nums.add(6.0);
        nums.add(2.230);
        nums.add(25.01);
        nums.add(10.420);
        
        ArrayListExample example = new ArrayListExample();
        double max = example.findMax(nums);
        System.out.println("Maximum value: " + max);
    }
}

ArrayListExample.main(null);

Homework:

(Paragraph Answer)

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

(Code Answer)

  1. Make your own algorithm using ArrayLists. Do not use the size and get methods, those are way too easy!