Reputation: 391
First I have two objects created like so...
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");
No surprises here, all obvious whats going on, but then I want to check them for equality! And I am looking to check all of their elements obviously to see if they are truly equal or not. So I call "System.out.println(recipeOne.equals(recipeTwo));" which will go here...
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;
}
Now I know it is incomplete and will only check the first Ingredient in recipeOne which is "Ingredients[]" and the first ingredient in recipeTwo, the copy, "tempRec.Ingredients[]". Now my question is, how do I check the rest of the locations and make sure they are all equal before sending the "okay-of-equality" ? Is there a way to go back into the for-loop and check the next spot, maybe store all the trues then when they're all figured out and finally return true? I'd rather not write out 10 if statements checking all the locations for whether they are null or not then checking to see if the ingredients are equal lol
(Almost forgot my Ingredient.equals(), here it is for reference but it works fine!)
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;
}
Upvotes: 1
Views: 150
Reputation: 359816
Invert the condition, and only return true
at the very end:
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;
}
Better still, use the existing library method to do the work for you: 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);
}
Upvotes: 2