Any simple examples for a Rubyist on how to use java clone the right way and the wrong way?

StackOverflow https://stackoverflow.com/questions/23583989

  •  19-07-2023
  •  | 
  •  

Frage

I'm a rubyist and have started learning java. Came across some dialog that says not to use clone() method in java or if I do, make sure to know what I'm doing with it. Java clone method seems to be a popular topic on stackoverflow but most questions have been about advanced topics related to why cloning is not working or shallow or deep copy etc. Don't know what to make of that. What about a few simple examples of how to use clone the right way and the wrong way?

It looks like clone is in the interface of an object but has absolutely no implementation. If there is no implementation why do I have to throw the cloneNotsupported exception? Could someone provide a comprehensive list of examples of how clone can be used the right way as well as the wrong way?

thank you in advance.

War es hilfreich?

Lösung

I think clone() could maybe used with your own, well defined, final data structure (or record) that is not exactly a class (has all public fields and no methods). Also, these fields should be either primitive data types, or immutable types (like Strings) so could be shared without problems.

Cloning such a structure by assigning all fields manually simply means more code, makes the maintenance more difficult (more changes after you add or remove a field) and I really do not understand what exactly benefits this brings.

C / C++ has an assignment statement for the structures to copy all fields in one go and in some cases does this transparently ("structure passed by value"). Java could use clone for the similar goal. After all, simply assigning a double value to a variable is a kind of cloning: all fields of the IEEE data structure (sign bit, exponent, fraction) are copied. Never used to be any fundamental problems with this. How this is different from cloning a final Point class with two public integer fields, x and y?

Most of arguments against clone() are valid for cases when the exact class of the instance in use is not known or it may be unknown invisible fields that may not get initialized correctly.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top