Cloning versus creating a new class

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; } 
+7
java instances
source share
4 answers

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

Wikipedia is a good article on why clone() has many flaws in Java.

Using copy constructors, create a constructor that takes an instance of the current class as a parameter, and copy all the 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 a parameter and returns an object containing the same values:

 public Foo copyFoo(Foo other) { Foo foo = new Foo(); foo.setBar(other.getBar()); foo.setBaz(other.getBaz()); } 
+10
source share

You could use a copy constructor instead of a Cloneable implementation, but it looks like you have a ModelEntry class ModelEntry so using clone might be the best approach. See this question for some pointers on what happened to Cloneable

+2
source share

I find this to be like everything else in programming: it depends on the specification of the object.

Try to make a very quick test: clone 100,000 objects and create the same number of objects and check how long it takes (System.currentTimeInMilis ()). Often a clone is faster.

And remember that there is one problem with the clone - when adding a new field, etc. you also need to change the clone () method.

+1
source share

A clone is not a good idea, as many programmers agree.

It is subject to errors. You must carefully override clone() . Forgetting the call to super.clone() is a popular mistake.

0
source share

All Articles