簡體   English   中英

Java,在數組上插入對象的方法,返回一個布爾值

[英]Java, method to insert an Object on an Array, returning a boolean

我很難理解我在Java中作為OOP簡介項目的一部分而獲得的任務。 所有名稱均已更改,但未完全翻譯。 我被要求完成以下方法:

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;

我的問題是,這將如何以及為什么會導致虛假? 我確實限制了農場的馬匹數量,但是我可以(並且正在計划)在調用該方法之前進行檢查。 這對我來說是不好的做法嗎?

最高的問候,JoãoSilva

除了馬數的限制外,我不認為這應該返回false。 盡管從理論上講,如果馬匹過多,則可能會耗盡堆空間,但是這種情況很可能會導致程序崩潰。

最好將馬匹數檢查在此功能中,而不是在此功能之外。 這樣一來,就不可能無意間插入超出允許范圍的馬匹。

您假設將始終有足夠的可用內存來分配一個有空間再容納Horse的陣列。

一種情況可能不正確,就是拋出了OutOfMemoryError

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM