The AP Computer Science A 5-hour live stream review is here!Β πŸ’»

Join us on May 5, 2021 for the 🌢️ AP Computer Science A Cram Finale for a last minute review to get all your questions answered!

πŸ“š

All Subjects

Β >Β 

πŸ’»Β 

AP Comp Sci A

Β >Β 

πŸ’Ύ

Unit 7

7.4 Developing Algorithms Using ArrayLists

6 min readβ€’november 16, 2020

Peter Cao

Caroline Koffke


7.4: Developing Algorithms Using ArrayLists

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<Integer> 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<Student> 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<Integer> 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<Integer> 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 is initializing the maxValue and minValue to 0. If all the values in the array are positive, it would incorrectly keep minValue at 0 (all the values are greater than 0, leaving 0 as the minimum). If all the values in the array are negative, it would incorrectly keep maxValue at 0 (all the values are less than 0, leaving 0 as the maximum). To counter these errors, initialize these to the first value in the array.

Finding a Sum

/** Sums up all elements in the ArrayList */ public static int sum(ArrayList<Integer> array) { int sum = 0; for (int number: array) { sum += number; //adds every element to sum } return sum; }

Finding a Mean

/** Finds the mean/average of the ArrayList */ public static int mean(ArrayList<Integer> array) { int sum = sum(array); // find the sum of the ArrayList, can be replaced with sum return (double) sum / (array.size()); //algorithm above }

Finding a Mode

/** Finds the mode of an ArrayList Prerequisite: The array must have a mode */ public static int mode(ArrayList<Integer> array) { int mostCommon = 0; int mostCommonFrequency = 0; for (int i = 0; i < array.size() - 1; i++) { //traverse through the ArrayList int currentFrequency = 1; for (int j = i + 1; j < array.size(); j++) { //traverse through rest of ArrayList if (array.get(j) == array.get(i)) { // if any element matches current element currentFrequency++; // being checked, add 1 to frequency } } if (currentFrequency > mostCommonFrequency) { mostCommon = array.get(i); // replaces current mode if new most common element mostCommonFrequency = currentFrequency; } } return mostCommon; // can also be modified to return the frequency }

Determining If All Values Have a Certain Property

/** Determines whether all values are even */ public static boolean isEven(ArrayList<Integer> array) { //Assume all values are positive first for (int number: array) { if (number % 2 == 1) { //If there is one value that is not positive, return false return false; } } return true; //No odd numbers were found }

Accessing All Consecutive Pairs/Triplets/Sequences of Length n of Elements

/** Returns all consecutive sequences of length n in the ArrayList */ public static void returnAllConsecutiveSequences(ArrayList<Integer> array, int length) { for (int i = 0; i <= array.size() - length; i++) { for (int j = 0; j < length; j++) { System.out.print(array.get(i+j) + " "); //2 loops, one to get the starting number } //the other to go through the sequences System.out.println(); } }

Checking if There are Duplicate Elements

/** Checks to see if there are duplicate elements */ public static boolean duplicates(ArrayList<Integer> array) { for (int i = 0; i < array.size() - 1; i++) { //traverse through the ArrayList for (int j = i + 1; j < array.size(); j++) { //traverse through rest of ArrayList if (array.get(j) == array.get(i)) { // if any element matches current element return true; // being checked, return true } } } return false; // if this point reached, no duplicates found }

Determining How Many Elements Fit a Criteria

/** Returns how many even numbers there are */ public static int evenFrequency(ArrayList<Integer> array) { int numberEven = 0; for (int number: array) { if (number % 2 == 0) { numberEven++; // increments every time an even integer is found } } return numberEven; }

Shifting Elements One Index Left

/** Shifts Elements One Index to the Left */ public static ArrayList<Integer> shiftLeft(ArrayList<Integer> array) { int firstItem = array.get(0) for (int i = 0; i < array.size() - 1; i++) { array.set(i, array.get(i+1)); // Does the shifting } array.set(array.size() - 1, firstItem) return array; }

Shifting Elements One Index Right

/** Shifts Elements One Index to the Right */ public static ArrayList<Integer> shiftRight(ArrayList<Integer> array) { int lastItem = array.get(array.size()- 1) for (int i = array.size() - 1; i > 0; i--) { array.set(i, array.get(i-1)); // Does the shifting } array.set(0, lastItem); return array; }

Reversing an Array

/** Reverses the ArrayList */ public static ArrayList<Integer> reverse(ArrayList<Integer> array) { ArrayList<Integer> newArray = new ArrayList<Integer>(); for (int i = 1; i <= array.size(); i++) { newArray.add(array.get(array.size() - i)); // places the items in the new ArrayList in // opposite order of the original } return newArray; }

Putting Items from an ArrayList into an Array

/** Transfers all ArrayList items into an Array */ public static int[] arrayListToArray(ArrayList<Integer> array) { int[] newArray = new int[array.size()]; for (int i = 0; i < array.size(); i++) { newArray[i] = array.get(i) } return newArray; }

Putting Items from an Array into an ArrayList

/** Transfers all Array items into an ArrayList */ public static ArrayList<Integer> arrayToArrayList(int[] array) { ArrayList<Integer> newArray = new ArrayList<Integer>(); for (int i: array) { newArray.add(i); } return newArray; }

Was this guide helpful?

πŸ’ͺ🏽 Are you ready for the Comp Sci exam?
Take this quiz for a progress check on what you’ve learned this year and get a personalized study plan to grab that 5!
START QUIZ
FREE AP comp sci a Survival Pack + Cram Chart PDF
Sign up now for instant access to 2 amazing downloads to help you get a 5
Browse Study Guides By Unit
πŸ™
Exam Reviews
πŸ–±
Unit 10: Recursion
βž•
Unit 1: Primitive Types
πŸ“±
Unit 2: Using Objects
πŸ–₯
Unit 3: Boolean Expressions and if Statements
πŸ•Ή
Unit 4: Iteration
βš™οΈ
Unit 5: Writing Classes
⌚️
Unit 6: Array
πŸ’»
Unit 8: 2D Array
πŸ–²
Unit 9: Inheritance
Join us on Discord
Thousands of students are studying with us for the AP Computer Science A exam.
join now