动态对象引用

时间:2014-10-13 16:44:24

标签: java oop object dynamic copy

我试图创建一个对象arrayList并遇到一个问题:我不知道如何动态创建一个特定成分的新对象/动态建立唯一引用,所以它指向一个唯一的对象,而不是打印出一些东西像这样:

椰子366

椰子366

椰子366

//列表中的所有椰子都引用了最后一个椰子,因此没有新的独特椰子容器对象

然后我试了一下:

allContainers.add(new Coconut());

然后访问列表中的最后一项,并在for循环迭代的当前索引处转换对象,替换空的新Coconut(),但是对此的赋值也不起作用..

有没有人知道在同一个Object的每个方法调用中添加唯一引用,因此值会有所不同,因为它会指向不同的对象? 有什么建议如何解决这个难题?

谢谢。

扩展示例代码:

ArrayList<TeaObjects> someTea = new ArrayList<TeaObjects>();
ArrayList<HealthyObjects> someHealth = new ArrayList<HealthyObjects>();

public void init {

someTea.add( new blackTea() );
someTea.add( new whiteTea() );
someTea.add( new greenTea() );
}


public void tea {

    // for loop checking for properties
    if (healthyTea) {


        // 1. Create a new instance dynamically of the lets say greenTea g1, where constructor is           empty

        // 2. add those properties to g1 =  (Cast ) (assign healthy properties)


        // 3. HealthyObjects.add(g1); // where g1 is dynamically created reference

    add to a list tea, so I want to achieve [new greenTea g1, new greenTea g2] to be in the list. I also want 



    }

}

1 个答案:

答案 0 :(得分:0)

当然,每次都要创建一个新实例。写一个拷贝构造函数:

public class Ingredient {
    private String name;

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

    // copy constructor
    public Ingredient(Ingredient duplicate) {
        this.name = duplicate.name;
    }
}