首先我创建了两个像这样的对象......
Recipe recipeOne = new Recipe("Pepperoni Pizza");
Ingredient one = new Ingredient("Dough", 1, UnitOfMeasurement.valueOf("Pounds"));
Ingredient two = new Ingredient("Sauce", 8, UnitOfMeasurement.valueOf("Ounces"));
Ingredient three = new Ingredient("Cheese", 10, UnitOfMeasurement.valueOf("Ounces"));
recipeOne.addIngredient(one);
recipeOne.addIngredient(two);
recipeOne.addIngredient(three);
RecipeBook.addRecipe(recipeOne);
Recipe recipeTwo = (Recipe) recipeOne.clone();
recipeTwo.addIngredient(recipeOne.Ingredients[0]);
recipeTwo.addIngredient(recipeOne.Ingredients[1]);
recipeTwo.addIngredient(recipeOne.Ingredients[2]);
RecipeBook.addRecipe(recipeTwo);
recipeTwo.setName("Pineapple Pizza");
这里没有惊喜,所有明显的事情都在发生,但后来我想检查它们是否平等!而且我希望明确检查它们的所有元素,看看它们是否真的相同。所以我称之为“System.out.println(recipeOne.equals(recipeTwo));”会在这里......
public boolean equals(Object obj){
if(obj instanceof Recipe){
Recipe tempRec = (Recipe) obj;
for(int j = 0 ; j < Ingredients.length ; j++){
if(Ingredients[j].equals(tempRec.Ingredients[j]) == true){
return true;
}
}
}
return false;
}
现在我知道它是不完整的,只会检查recipeOne中的第一个成分,即“Ingredients []”和recipeTwo中的第一个成分,副本“tempRec.Ingredients []”。现在我的问题是,如何在发送“等于平等”之前检查其余的位置并确保它们都是平等的?有没有办法回到for-loop并检查下一个位置,也许存储所有的真相然后当它们全部被弄清楚并最终返回true?我宁愿不写出10个if语句检查所有位置是否为空,然后检查成分是否相等lol
(差点忘了我的Ingredient.equals(),这里仅供参考,但效果很好!)
public boolean equals(Object obj){
if(obj instanceof Ingredient){
Ingredient tempIngred = (Ingredient) obj;
if(Name.equals(tempIngred.getName()) && Quantity == (tempIngred.getQuantity()) &&
unitOfMeasurement.equals(tempIngred.getUnit()))
return true;
}
return false;
}
答案 0 :(得分:2)
反转条件,最后只有return true
:
public boolean equals(Object obj){
if (!obj instanceof Recipe) return false;
if (obj == this) return true;
Recipe tempRec = (Recipe) obj;
for(int j = 0 ; j < Ingredients.length ; j++) {
if(!Ingredients[j].equals(tempRec.Ingredients[j])) {
return false;
}
}
return true;
}
更好的是,使用现有的库方法为您完成工作:Arrays.equals(Object[] a1, Object[] a2)
。
public boolean equals(Object obj){
if (!obj instanceof Recipe) return false;
if (obj == this) return true;
Recipe tempRec = (Recipe) obj;
return Arrays.equals(this.Ingredients, tempRec.Ingredients);
}