Alex Rivera | Logout

Cloning vs. Instantiating a new class

Asked 2010-09-14T09:28:51.017
9

Is cloning good practice in this case? How to do it better?

public ModelCollection startParsing() {

   return parseFeed(new ModelSpecialEntry); 
}

public ModelCollection parseFeed(ModelEntry pattern)  {

   ModelCollection modelCollection = new ModelCollection();

   while( condition ) {

     //TODO: Is cloning the best solution?
     ModelEntry model = (ModelEntry) pattern.clone();



     model.parse();

     //add this item to an collection
     modelCollection.add(model);


   }

   return modelCollection;
}
Edit
Report

1 Answer

10

Cloning is rarely a good idea in Java. Try other techniques such as Copy constructors or Factory methods.

Wikipedia has a nice article on why clone() has many disadvantages in Java.

Using copy constructors, create a constructor that takes an instance of the current class as parameter, and copy all fields in the local class:

public class Foo {

    private String bar;
    private String baz;

    public Foo(Foo other) {
        this.bar = other.bar;
        this.baz = other.baz;
    }

}

Using factory methods, create a method that takes your object as parameter and return an object containing the same values:

public Foo copyFoo(Foo other) {
    Foo foo = new Foo();
    foo.setBar(other.getBar());
    foo.setBaz(other.getBaz());
}
answered 2010-09-14T09:43:53.117

Your Answer