I’m having a difficult time trying to understand an assignment I was given as a part of a OOP Introduction project in Java. All names are changed, not exactly translated.
I’m asked to complete the following method:
public boolean insertHorse(Horse horse) {
return true;
}
The method signature can’t be changed, I’m supposed to add the horse on the array of horses of the class the method is in, and to return true if it was inserted with success, or false otherwise.
So this is what I’ve done:
public boolean insertHorse(Horse horse) {
//Create a temp array with length equal to h
Horse[] temp = new Horse[this.horses.length+1];
//copy the horses to the temp array
for (int i = 0; i < horses.length; i++){
temp[i] = horses[i];
}
//add the horse on the temp array
temp[temp.length-1] = horse;
//change the reference of the old array to the temp one
veiculos = temp;
return true;
My problem is, how and why would this ever give false? I do have a limitation to the number of horses of a farm, however I can (and was planning) on checking that before calling the method. Is this a bad practice of me?
Highest regards,
João Silva
I can’t think of any reason this should return false, except for the limitation of number of horses. Although in theory you could run out of heap space if there were too many horses, that condition would probably cause your program to crash anyway.
It would be good practice to put the number of horses check in this function instead of outside of it. That way, it wouldn’t be possible to accidentally insert more horses than allowed.