How to deep clone the integer object or any other primitive data class object? What is a similar method to clone() in SObject for Integer?

Integer a = 1232;
// ...
Integer b = a.clone(); // does not compile

You can't. Primitives are immutable, which also means it's safe to use references to them, because they can't be accidentally mutated.

  • I'm not sure the use of the term "immutable" is quite how I would put it. I'd think it better to describe them as being stored by value rather than as referenced objects. You can then consider the "Object" (such as Integer or Boolean) that appears to be their accessible type as simply an autoboxing of the underlying primitive value, and where all assignments to primitive variables perform auto-unboxing (so hold the value, not the reference). After all, if I have an Apex class with an Integer attribute or property, I can change the value of that primitive member. – Phil W Feb 16 at 17:21
  • 2
    @PhilW I've done research on this topic, being that I like poking and prodding Salesforce internals. While Java has actual primitives (stored by value), Apex primitives are real objects that use real heap, and are immutable objects. You are free to modify a non-final property of a class, but you'll never actually modify the primitive object that it points to. See, for example, this. Note that this is a cool trick Apex plays, as it saves heap usage when you use primitive reference values, while giving the illusion of storing by value. – sfdcfox Feb 16 at 17:44
  • 1
    Always nice to get a bit of insight into the internals. I stand entirely corrected :D – Phil W Feb 16 at 18:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.