Is it a clone safe for transferring enumerated clone classes?

I have a simple class that contains a skeleton for a much larger, more cumbersome class. This whole skeleton is a string identifier, an enumeration of the type, and some flags for the parameters.

I would like to be able to clone this skeleton, but I do not know if enumeration is safe for clones (go by value). I think this is not the case, as they are considered classes (follow the link). Is it safe to just list an enumeration in a clone?

Example for clarity:

class A { String id; Enum state; int flags; A clone() { A ret = new A(); ret.id = id; ret.state = state; // Am I safe here? ret.flags = flags; return ret; } } 
+4
source share
2 answers

An enum instance, by definition, is a singleton. There is only one instance of each instance of enum, by design. Therefore, obviously, the only thing you can do is copy the link.

+11
source

JB Nizet's answer is correct. But also, just in case you tried to override Object.clone() , remember that the official way to clone objects in Java looks something like this:

 class A implements Cloneable { String id; Enum state; int flags; public A clone() { A ret = (A) super.clone(); ret.id = id; ret.state = state; // Enum is a singleton, so this is ok ret.flags = flags; return ret; } } 

Note that you must call (A) super.clone() instead of new A() and that your class must implement the Cloneable interface.

+4
source

Source: https://habr.com/ru/post/1391347/


All Articles