我很難理解我作爲Java的OOP簡介項目的一部分給出的任務。所有名字都改變了,沒有完全翻譯。 我要求完成了以下方法:Java,在數組中插入對象的方法,返回一個布爾值
public boolean insertHorse(Horse horse) {
return true;
}
方法簽名不能改變,我應該添加類的方法是在馬的陣列上的馬,並如果插入成功則返回true,否則返回false。 所以這是我做了什麼:
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;
我的問題是,如何以及爲什麼會這個不斷給假?我確實對農場的馬數有限制,但是我可以(並正在計劃)在調用該方法之前檢查它。這對我來說不好嗎?
崇高的敬意, 若昂·席爾瓦
您可以通過簡單地返回「false」而無需其他操作來「正確」實現該功能。 –
@HotLicks然後我會失去返回真實的可能性,我想在任務的上下文中,我必須檢查我是否在數組中允許的馬匹的最大值,並且如果我是 - >返回false – Kirag
它仍然會滿足「契約」 - 不變將被保留。 –