1

首先我有两个像这样创建的对象......

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[]”。现在我的问题是,如何在发送“okay-of-equality”之前检查其余位置并确保它们都相等?有没有办法回到for循环并检查下一个点,也许存储所有的真值,然后当它们都被找出并最终返回真值时?我宁愿不写出 10 个 if 语句检查所有位置是否为空,然后检查成分是否相等,哈哈

(差点忘了我的 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;   

}
4

1 回答 1

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);
}
于 2013-02-11T23:20:02.220 回答