SequencedCollection Class and the AP CSA Free Response Questions
For the AP Computer Science A (AP CSA) 2023 question 3 free response question, students were asked to clean data in an ArrayList
. The canonical solution has students iterating backwards through the list and removing elements that are not in the defined range. Removing elements from a list is a skill that many students find challenging. Students often make one of the following mistakes:
- They iterate starting at the beginning of the list and then skip elements as they remove items.
- Iterate from the end of the list, but make off by one errors.
The SequencedCollection
class, released in Java 21, contains methods:
- getLast()
- getFirst()
- removeLast()
- removeFirst()
Below, I propose an alternate solution using these new methods.
public void cleanData (double lower, double upper) {
ArrayList<Double> original = new ArrayList<>();
ArrayList<Double> cleaned = new ArrayList<>();
for (int i = 0; i < temperatures.size(); i++)
original.add(temperatures.get(i));
for (Double _ : temperatures) {
double temp = original.getFirst();
if (temp >= lower && temp <= upper {
cleaned.add(temp);}
original.removeFirst();
}
temperatures = cleaned;
}
A few important notes with this solution:
- To use
removeFirst
(or removeLast
), I needed a copy of the original ArrayList
and to build a new list with the correct data. If you don't and try to use the original list, once a value is in range, you start to repeatedly access only the last element of the list. (Yes, I'm guilty of this attempt. LOL)
- You can use
getFirst
/ removeFirst
OR getLast
/ removeLast
. Since we are storing the values we want in the new ArrayList cleaned
and then removing them from that list, we will still access each element.
- You need to iterate the entire original length of the
ArrayList
. You can use a for loop that iterates temperatures.size()
number of times. But, since I wanted to highlight the use of unnamed variables for you, I used a for each loop.
- I reversed the logic to keep the values in the range, rather than discard the values in the
ArrayList
not in the range.
Now, I'm not at all claiming this solution is better than that of the canonical. I'm just raising that this works. And could be a solution that students use to get full credit on the exam.
Unnamed Variables and Patterns
When variable declarations are required, but the variable itself is not used, you can use an underscore ( _
) instead. In the example above, we are using a for loop to iterate through the list, but we are not using the data that would be accessed with the for loop, just using it as a way to iterate the correct number of times. So instead of:
for (Double d : temperatures) {
since we aren't using d
in the code, we can write:
for (Double _ : temperatures) {
To learn more about Unnamed Variables and Patterns (JEP 456: Unnamed Variables & Patterns), click here.