Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net MemberwiseClone vs Java Clone

Tags:

java

c#

.net

I'm converting C# code to Java. There are many different places that relies on .Net MemberwiseClone in the code I'm converting.

It seems that they both make shallow copy. So is it possible to simply replace these calls with Java's clone()? I want to make sure there are not any minor differences that would cause difficult to fix bugs.

like image 624
Caner Avatar asked Sep 21 '11 13:09

Caner


People also ask

Why use MemberwiseClone?

The function MemberwiseClone creates a new objects whose fields are bit-for-bit copies of those in the original structure. It is a necessary part of any inheritable class which allows cloning without use of Reflection or serialization, but it is only a small piece of the overall puzzle.

What is the method MemberwiseClone () doing?

The MemberwiseClone method creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed.

What is cloneable object in C#?

In C#, Clone() is a String method. It is used to clone the string object, which returns another copy of that data. In other words, it returns a reference to this instance of String. The return value will be only another view of the same data. Clone method called directly on current String instance.


1 Answers

Assuming the clone() call in Java is just calling the Object.clone() implementation, then I believe they have the same behaviour:

  • Another object of the same class is created
  • The fields are copied (up and down the inheritance hierarchy)
  • All copies are performed in a shallow way
  • No user-specified code is executed (constructors etc)
like image 172
Jon Skeet Avatar answered Oct 05 '22 17:10

Jon Skeet