Skip Top Navigation Bar

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:

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:

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.