[英]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.