Swapping elements in an array Java

Tags: , ,



I am working on a classes challenge in school. We have to great a Boat class and Harbor class. I have gotten every test to work except the final test of where boats are parked in the Harbor. The Harbor constructor contains an array for the Harbor.

The test we have to run is below and the code I have written (for the Harbor class) is below that. Fresh eyes are helpful!

@Test
    void testboatStock()
    {
        Boat boat1 = new Boat("BMC", Color.GREEN);
        Boat boat2 = new Boat("BMX", Color.RED);
        Boat boat3 = new Boat("UXB", Color.YELLOW);
        
        Harbor stock = new Harbor(5);
        assertEquals(null, stock.getBoatAt(0));
        assertEquals(null, stock.getBoatAt(1));
        assertEquals(null, stock.getBoatAt(2));
        assertEquals(null, stock.getBoatAt(3));
        assertEquals(null, stock.getBoatAt(4));
        
        // Hint: parkBoatAt is not just a accessor, and not just a mutator
        assertEquals(null, stock.parkBoatAt(boat1, 3));
        Boat retrievedBoat = stock.parkBoatAt(boat2, 3);
        assertEquals(boat1, retrievedBoat);
        retrievedBoat = stock.parkBoatAt(boat3, 3);
        assertEquals(boat2, retrievedBoat);
        Boat[] inventory = stock.getInventory();
        assertArrayEquals(new Boat[]{null, null, null, boat3, null}, inventory);
        stock.parkBoatAt(boat2, 1);
        assertArrayEquals(new Boat[]{null, null, null, boat3, null}, inventory); // this is correct!
        assertArrayEquals(new Boat[]{null, boat2, null, boat3, null}, stock.getInventory());
    }
public class Harbor
{
    private int slipNumber = 0;
    private Boat[] boats = new Boat[slipNumber];
    
    public Boat parkBoatAt(Boat boat, int slipNumber)
    {
        boat = boats[slipNumber];
        if(boats[slipNumber]== boat)
        {
            
            return boat;
        }
        else
        {
            return null;
        }
    }
    public Boat getBoatAt(int slipNumber)
    {
        if(boats[slipNumber]==null)
        {
            return null;
        }
        return boats[slipNumber];
    }
    
    public Boat[] getInventory()
    {
        return boats;
    }
    public Harbor(int numberOfSlips)
    {
         boats = new Boat[numberOfSlips];
    }
    public Harbor()
    {
        
    }

}

Answer

public Boat parkBoatAt(Boat newBoat, int slipNumber) {   // 1
  Boat oldBoat = boats[slipNumber];
  boats[slipNumber] = newBoat;
  return oldBoat;
}

public Boat[] getInventory() {
  return Arrays.copyOf(this.boats, this.boats.length);   // 2
}
  1. You need to return the previous value of the element in array.
  2. You need to copy the array to make sure it is unchanged.


Source: stackoverflow