Consider a software system that models a horse barn. Classes that represent horses implement the following interface.

```public interface Horse
{
/** @return the horse's name */
String getName();

/** @return the horse's weight */
int getWeight();
}```

A horse barn consists of N numbered spaces. Each space can hold at most one horse. The spaces are indexed starting from 0; the index of the last space is N – 1. No two horses in the barn have the same name. The declaration of the HorseBarn class is shown below.

Write the HorseBarn method consolidate. This method consolidates the barn by moving horses so that the horses are in adjacent spaces, starting at index 0, with no empty spaces between any two horses. After the barn is consolidated, the horses are in the same order as they were before the consolidation.

```public class HorseBarn
{
/** The spaces in the barn. Each array element holds a reference to the horse
* that is currently occupying the space. A null value indicates an empty
* space.
*/
private Horse[] spaces;

/** Consolidates the barn by moving horses so that the horses are in
*  adjacent spaces, starting at index 0, with no empty space between
*  any two horses.
* Postcondition: The order of the horses is the same as before the
*  consolidation.
*/
public void consolidate()
{ /* to be implemented in part (b) */ }
}```

## 如何解题

0:00

Which loop should you use to loop through all the digits of the number?

1

How do we check if the space at the current index isn’t null?

3

```public void consolidate() {
Horse[] newSpaces = new Horse[this.spaces.length];
int nextSpot = 0;
for (int i = 0; i < this.spaces.length; i++) {
if (this.spaces[i]!=null) {
newSpaces[nextSpot] = this.spaces[i];
nextSpot++;
}
}
this.spaces = newSpaces;
}```