Search code examples
javaargumentsclone

How to use arguments in cloned object?


So let say I have such prototyping:

private static Hashtable<String, Furniture> map  = 
                        new Hashtable<String, Furniture>();

public My_product() {
    loadCache();
}

public My_Product createProduct(String type, String name) {
    Furniture cachedproduct = map.get(type);
    return  (Furniture) cachedproduct.clone();
}

private static void loadCache() {
    Sub_product1 pr1 = new Sub_product1(null);
    map.put("pr1", pr1);
    Sub_product2 pr2 = new Sub_product2(null);
    map.put("pr2", pr2);
}   

So when I make an instance of an object, I don't know what value will be entered after cloning it (creating object using cloning). So I chosen null value for object instance. But when I clone it then I know what value needs to be assigned for that object. So how could I specify while cloning to put some value instead of null one from object instance?

As you can see in method createProduct method, there is argument called name. I would like that name to be used in cloned object, but how could I do that?


Solution

  • Can you use setter methods?

    public My_Product createProduct(String type, String name) {
        Furniture cachedproduct = map.get(type);
        Furniture clonedProduct = (Furniture) cachedproduct.clone();
        clonedProduct.setType(type);
        clonedProduct.setName(name);
        return clonedProduct;
    }
    

    However, I'm still not clear on the whole idea of this cloning of cached objects from the map. Is your product instantiation very expensive? What's the trick?