gpt4 book ai didi

Java,在数组上插入对象的方法,返回 boolean 值

转载 作者:太空宇宙 更新时间:2023-11-04 07:54:36 25 4
gpt4 key购买 nike

我在尝试理解作为 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;

我的问题是,这如何以及为什么会给出错误?我确实对农场的马匹数量有限制,但是我可以(并且计划)在调用该方法之前检查这一点。这是我的不好做法吗?

致以最崇高的敬意,若昂·席尔瓦

最佳答案

除了马匹数量的限制之外,我想不出任何原因应该返回 false。尽管从理论上讲,如果马太多,您可能会耗尽堆空间,但这种情况可能会导致您的程序崩溃。

最好将马匹数量检查放在这个函数中而不是放在函数之外。这样,就不可能意外插入超出允许数量的马匹。

关于Java,在数组上插入对象的方法,返回 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13812613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com