对象数组实例的深度复制,Java

She*_*kie 5 java arrays object deep-copy

我在我的 main 中制作了一个对象Recipe recipeOne = new Recipe("Pepperoni Pizza");

该对象是此处定义和构造的对象数组的实例!

public class Recipe implements Cloneable{

String Name;

final int INGREDIENT_ARRAY_MAX = 10;

Ingredient Recipe[] = new Ingredient[INGREDIENT_ARRAY_MAX];

public Recipe(String name){

    Name = name;

}
Run Code Online (Sandbox Code Playgroud)

所以我想用这条线制作这个对象的深层副本Recipe ressippi = (Recipe) recipe.clone();,它把我发送到这里!

public Object clone(){

    Recipe cloneRec = new Recipe(Name);

    return cloneRec;

}
Run Code Online (Sandbox Code Playgroud)

我知道这目前是一个浅拷贝,因为该方法只传递引用,所以如果我尝试对我的新对象(它是recipeOne 的克隆)进行名称更改...它将更改它们的两个名称。显然我不希望这样,我对此很迷茫,有人可以帮忙吗?

编辑:@Rohit Jain

我的 Recipe 类和 Ingredient 类(菜谱数组保存的对象)都有 toString 方法,并且 Recipe 调用配料,以便以漂亮的小格式将其全部打印出来。当我在我的“recipeOne”对象(称为意大利辣香肠披萨的那个)上调用它时,我得到“意大利辣香肠披萨:1.0 磅面团,8.0 盎司酱汁,10.0 盎司奶酪”

然后我继续创建 ressippi 对象并将其设置为recipeOne 的克隆,所以从这里开始一切都很好...然后我将 ressippi 的名称更改为“Pineapple Pizza”,打印效果很好,但它不打印recipeOne 的 3 个成分对象存储,这是它应该做的!

Kev*_*sox 3

向配方类添加复制构造函数,该构造函数创建配方的新实例并复制原始配方中的所有字段。

菜谱.java

public class Recipe implements Cloneable {

    String name;

    final int INGREDIENT_ARRAY_MAX = 10;

    Ingredient[] ingredients = new Ingredient[INGREDIENT_ARRAY_MAX];

    public Recipe(String name) {
        this.name = name;
    }

    //Copy Constructor
    private Recipe(Recipe recipe){
        this.name = recipe.name;
        for(int x = 0; x < recipe.ingredients.length; x++){
            this.ingredients[x] = recipe.ingredients[x];
        }
    }

    public static Recipe newInstance(Recipe recipe){
        return new Recipe(recipe);
    }

    //Debug Method
    public static void printRecipe(Recipe recipe){
        System.out.println("Recipe: " + recipe.name);
        for(Ingredient i:recipe.ingredients){
          if(i != null && i.getName() != null){
              System.out.println("Ingredient: " + i.getName());           
          }
        }
    }

    //Test Method
    public static void main(String[] args) {
        Recipe recipe = new Recipe("Chicken Soup");
        recipe.ingredients[0] = new Ingredient("Chicken");
        recipe.ingredients[1] = new Ingredient("Broth");

        Recipe copy = new Recipe(recipe);
        copy.ingredients[2] = new Ingredient("Rice");
        copy.name = "Chicken Rice Soup";

        printRecipe(recipe);
        printRecipe(copy);
        System.out.println(recipe == copy);
        System.out.println(recipe.ingredients == copy.ingredients);
    }
}
Run Code Online (Sandbox Code Playgroud)

成分.java

public class Ingredient {

    private String name;

    public Ingredient(String name){
        this.name = name;
    }

    public String getName() {
        return name;
    }


    public void setName(String name) {
        this.name = name;
    }
}
Run Code Online (Sandbox Code Playgroud)