Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloning vs. Instantiating 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;
}
like image 641
OneWorld Avatar asked Sep 14 '10 09:09

OneWorld


People also ask

What is the difference between clone and copy constructor?

Copy Constructor vs. However, the copy constructor has some advantages over the clone method: The copy constructor is much easier to implement. We do not need to implement the Cloneable interface and handle CloneNotSupportedException. The clone method returns a general Object reference.

Does clone create a new object?

Clone() method in Java. Object cloning refers to the creation of an exact copy of an object. It creates a new instance of the class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this object. In Java, there is no operator to create a copy of an object.

What is the meaning of class clone?

The object cloning is a way to create exact copy of an object. The clone() method of Object class is used to clone an object. The java. lang. Cloneable interface must be implemented by the class whose object clone we want to create.

Why do we need clone in Java?

The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by using the new keyword, it will take a lot of processing to be performed, so we can use object cloning.


1 Answers

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());
}
like image 66
Vivien Barousse Avatar answered Sep 30 '22 07:09

Vivien Barousse