2012 AP CSA FRQ 2: HorseBarn
Topic: Arrays & Consolidation
Skills: Array traversal, null handling, consolidation algorithm
Unit: Unit 4 (Data Collections) (2025-2026 AP CSA)
Points: 9 | Time: ~22 minutes
Part (a)
Write the findHorseSpace method that finds a horse by name.
Solution
public int findHorseSpace(String name)
{
for (int i = 0; i < spaces.length; i++)
{
if (spaces[i] != null && spaces[i].getName().equals(name))
{
return i;
}
}
return -1;
}Part (b)
Write the consolidate method that moves all horses to the front.
Solution
public void consolidate()
{
Horse[] newSpaces = new Horse[spaces.length];
int index = 0;
for (int i = 0; i < spaces.length; i++)
{
if (spaces[i] != null)
{
newSpaces[index] = spaces[i];
index++;
}
}
spaces = newSpaces;
}Key Concepts
Common Mistakes
Official Resources
Author: Tanner Crow - AP CS Teacher, 11+ years