【发布时间】:2012-12-11 02:19:58
【问题描述】:
我很难理解作为 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”而不做其他任何事情。
-
@HotLicks 然后我会失去返回真实的可能性,我想在分配的上下文中我必须检查我是否在数组中允许的马的最大值,如果我是 - > 返回错误
-
它仍然会满足“契约”——不变量会被保留。
标签: java arrays validation boolean