zuai-logo

Developing Algorithms Using ArrayLists

Caleb Thomas

Caleb Thomas

6 min read

Listen to this study note

Study Guide Overview

This study guide covers standard algorithms for ArrayLists including: modifying array values and object instance variables, finding minimum/maximum, sum, mean, and mode. It also explains how to determine if all values meet a criteria, access consecutive sequences, check for duplicates, count elements fitting a criteria, shift elements left/right, reverse an ArrayList, and convert between ArrayLists and arrays.

Standard Algorithms

Using the traversals and methods that we have learned in the previous two topics, we can make the same algorithms that we have developed for arrays (see Topic 6.4) with slight changes. Here, we will have a snippet for each algorithm you are expected to know, with each snippet annotated for you.

Modifying Array Values

/** Doubles each element of the ArrayList */ public static void doubleArray(ArrayList array) { for (int i = 0; i < array.size(); i++) { array.set(i, array.get(i) * 2); // doubles each individual element } }

Modifying Instance Variables of Objects in an Array

/** Represents a student */ public class Student { private String name;

/** Sets the name of the Student */ public void setName(String name) { this.name = name; }

/** Other instance variables, methods, and constructors not shown / } // IN ANOTHER CLASS /* Resets all students' names */ public static void doubleArray(ArrayList array, String defaultName) { for (Student student: array) { student.setName(defaultName); // Sets each student's name to a default name } }

Finding the Minimum and Maximum

/** Finds the maximum */ public static int maximum(ArrayList array) { int maxValue = array.get(0); for (int number: array) { if (number > maxValue) { //if new max value found, replace current maxValue maxValue = number; } } return maxValue; }

/** Finds the minimum */ public static int minimum(ArrayList array) { int minValue = array.get(0); for (int number: array) { if (number < minValue) { //if new min value found, replace current minValue minValue = number; } } return minValue; }

A common mistake ...

Question 1 of 18

What will be the output of the ArrayList numbers after executing doubleArray(numbers) if numbers initially contains [1, 2, 3]?

[1, 2, 3]

[2, 4, 6]

[1, 4, 9]

[0, 0, 0]