Topics Covered:
Traversing: Traversal is when each element in an array or array list is accessed. This is mainly done through for and while loops so that elements are iterated through sequentially.
Parameters: There are variables that are passed into methods. For arrays and array lists, methods often have parameters that specify which array the passage should be performed upon.
Algorithms: Algorithms are the general overview of how operations are performed to manipulate or search through arrays.
Array Declaration: The data type in the array and the size of array is defined. In AP CSA, Java utilizes ‘int[] myArray;’ to declare. In the example, this would be an array with integer values.
Extraneous: These are extraneous elements that are not a part of the array/array list.
Differences between Arrays and ArrayLists:
Size
Arrays have a fixed size, while ArrayLists are resizable. They accommodate however many elements are needed.
Containing Data Type
Arrays can hold only one type of data inside of them while ArrayLists can have a mix of different types of data objects.
Performance
Arrays are more memory-efficient because they don’t have the capability to dynamically re-size themselves like ArrayLists do.
Common Questions:
Array Initialization and Manipulation:
- Initializing arrays with specific sizes
- Traversing arrays using loops
- Searching for elements within arrays
ArrayList Algorithms:
- Implementing searching algorithms within arrays or ArrayLists
- Creating custom functions to perform certain tasks on ArrayLists
Array and ArrayList Traversal:
- Iterating through an array to perform specific operations on elements within the array or ArrayList
- Creating conditional statements within the code to process certain new elements or go through existing elements in the arrays
Past AP Exam FRQs: 2023 FRQ #3
public class WeatherData
{
private ArrayList<Double> temperatures;
public void cleanData(double lower, double upper);
public int longestHeatWave(double threshold);
}
Part (a) Question:
Write the cleanData method, which modifies the temperatures instance variable by removing all values that are less than the lower parameter and all values that are greater than the upper parameter. The order of the remaining values in temperatures must be maintained.
Finish the cleanData method.
My attempt at part (a):
public void cleanData(double lower, double upper)
{
for (int i = temperatures.size() - 1;)
{
double temp = temperatures.get(i);
if (temp < lower || temp > upper)
{
temperatures.remove(i);
}
}
}
Correct answer for part (a):
public void cleanData(double lower, double upper)
{
// Iterate through the 'temperatures' ArrayList in reverse order to safely remove elements
for (int i = temperatures.size() - 1; i >= 0; i--)
{
// Get the temperature at the current index
double temp = temperatures.get(i);
// Check if the temperature is outside the specified range [lower, upper]
if (temp < lower || temp > upper)
{
// If the temperature is outside the range, remove it from the ArrayList
temperatures.remove(i);
}
}
}
Running code for part (a)
import java.util.ArrayList;
public class TemperatureDataCleaner {
private ArrayList<Double> temperatures;
public TemperatureDataCleaner() {
temperatures = new ArrayList<>();
}
public void addTemperature(double temperature) {
temperatures.add(temperature);
}
public void cleanData(double lower, double upper) {
// Iterate through the 'temperatures' ArrayList in reverse order to safely remove elements
for (int i = temperatures.size() - 1; i >= 0; i--) {
// Get the temperature at the current index
double temp = temperatures.get(i);
// Check if the temperature is outside the specified range [lower, upper]
if (temp < lower || temp > upper) {
// If the temperature is outside the range, remove it from the ArrayList
temperatures.remove(i);
}
}
}
public static void main(String[] args) {
TemperatureDataCleaner dataCleaner = new TemperatureDataCleaner();
// Add some sample temperatures to the ArrayList
dataCleaner.addTemperature(25.0);
dataCleaner.addTemperature(28.5);
dataCleaner.addTemperature(30.2);
dataCleaner.addTemperature(22.7);
dataCleaner.addTemperature(32.8);
// Print the original temperatures
System.out.println("Original Temperatures: " + dataCleaner.temperatures);
// Specify the lower and upper bounds for cleaning the data
double lowerBound = 25.0;
double upperBound = 30.0;
// Clean the data based on the specified bounds
dataCleaner.cleanData(lowerBound, upperBound);
// Print the cleaned temperatures
System.out.println("Cleaned Temperatures: " + dataCleaner.temperatures);
}
}
TemperatureDataCleaner.main(null);
Original Temperatures: [25.0, 28.5, 30.2, 22.7, 32.8]
Cleaned Temperatures: [25.0, 28.5]
Reflection on part (a):
I was very close to getting the correct answer, except I made an error when formulating the for loop.
In my answer, there is no loop condition specified within the parenthetical.
This is not following what the question is asking for. I need to have the for loop continue for as long as ‘i’ is greater than or equal to 0, while the ‘i–’ part means that ‘i’ is decreasing by one as each consecutive iteration goes on.
Next time, I need to make sure that my loop is effective in going through the iterations of the elements in the array.
Part (b) Question:
Write the longestHeatWave method, which returns the length of the longest heat wave found in the temperatures instance variable. A heat wave is a sequence of two more consecutive days with a daily high temperature greater than the parameter threshold. The temperatures instance variable is guaranteed to contain at least one heat wave based on the threshold parameter.
Complete method longestHeatWave.
My attempt at part (b):
public int longestHeatWave(double threshold)
{
int waveLength = 0;
int maxWaveLength = 0;
for (double temp : temperatures)
{
if (temp > threshold)
{
waveLength++;
if (waveLength > maxWaveLength)
{
maxWaveLength = waveLength;
return maxWaveLength;
}
}
}
}
Correct answer for part (b):
public int longestHeatWave(double threshold) {
// Initialize variables to keep track of the current heat wave length and the maximum heat wave length.
int waveLength = 0; // Current heat wave length.
int maxWaveLength = 0; // Maximum heat wave length observed so far.
// Loop through the array of temperatures.
for (double temp : temperatures) {
// Check if the current temperature is above the specified threshold.
if (temp > threshold) {
// If it is, increment the current heat wave length.
waveLength++;
// Check if the current heat wave length is greater than the maximum observed so far.
if (waveLength > maxWaveLength) {
// If it is, update the maximum heat wave length.
maxWaveLength = waveLength;
}
} else {
// If the current temperature is not above the threshold, reset the heat wave length to zero.
waveLength = 0;
}
}
// Return the maximum heat wave length observed in the array.
return maxWaveLength;
}
Running Code for Part (b)
public class HeatWaveAnalyzer {
private double[] temperatures;
public HeatWaveAnalyzer(double[] temperatures) {
this.temperatures = temperatures;
}
public int longestHeatWave(double threshold) {
// Initialize variables to keep track of the current heat wave length and the maximum heat wave length.
int waveLength = 0; // Current heat wave length.
int maxWaveLength = 0; // Maximum heat wave length observed so far.
// Loop through the array of temperatures.
for (double temp : temperatures) {
// Check if the current temperature is above the specified threshold.
if (temp > threshold) {
// If it is, increment the current heat wave length.
waveLength++;
// Check if the current heat wave length is greater than the maximum observed so far.
if (waveLength > maxWaveLength) {
// If it is, update the maximum heat wave length.
maxWaveLength = waveLength;
}
} else {
// If the current temperature is not above the threshold, reset the heat wave length to zero.
waveLength = 0;
}
}
// Return the maximum heat wave length observed in the array.
return maxWaveLength;
}
public static void main(String[] args) {
// Define an array of temperatures for testing.
double[] temperatureData = { 28.0, 30.0, 32.0, 25.0, 31.0, 33.0, 34.0, 29.0, 30.5, 31.5, 30.0 };
// Create an instance of HeatWaveAnalyzer with the temperature data.
HeatWaveAnalyzer analyzer = new HeatWaveAnalyzer(temperatureData);
// Specify the threshold temperature for heat waves.
double threshold = 30.0;
// Calculate and print the longest heat wave length.
int longestWaveLength = analyzer.longestHeatWave(threshold);
System.out.println("Longest Heat Wave Length: " + longestWaveLength);
}
}
HeatWaveAnalyzer.main(null);
Longest Heat Wave Length: 3
Reflection on part (b):
I messed up on this one, since I immediately returned the wavelength. This would only return the length of the first heat wave that is encountered in the array, but this is not the objective.
I had to correctly iterate through all the objects in the array and then find and return the length of the longest heat wave amongst the objects. Next time, I need to make sure that my code is doing exactly what the question is asking for.
Overall Reflection:
Based on the scoring criteria, I likely would’ve received a 6/9 on this FRQ. There are a lot of learnings, with my primary weakness with this type of FRQ being with the loops completing the tasks that the question are asking for.
The scoring criteria is below.
FRQ Feedback:
Highlighting Related Concepts
Adding Data to Arrays
public class ArrayExample {
public static void main(String[] args) {
int[] array = new int[3];
// Adding data to the array
array[0] = 1;
array[1] = 2;
array[2] = 3;
// Changing data at a specific index
array[1] = 10;
// Displaying the updated array
System.out.print("Updated Array: ");
for (int num : array) {
System.out.print(num + " ");
}
}
}
ArrayExample.main(null);
Updated Array: 1 10 3
Displaying Array/ArrayList by columns, as well as by rows horizontally
public class ArrayDisplay {
public static void main(String[] args) {
int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
// column display type
System.out.println("Array Displayed by Columns:");
for (int col = 0; col < matrix[0].length; col++) {
for (int row = 0; row < matrix.length; row++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println(); // lets print
}
}
}
ArrayDisplay.main(null);
Array Displayed by Columns:
1 4 7
2 5 8
3 6 9
Additional Resources to Research about Arrays & ArrayLists
Oracle Documentation: https://docs.oracle.com/javase/tutorial/
CodingBat Java: https://codingbat.com/java
AP CSA CED: https://apcentral.collegeboard.org/courses/ap-computer-science-a