Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

Is there any way to compare two primitives to find out if they are not only the same value but actually the same object?

share|improve this question
add comment

2 Answers 2

up vote 6 down vote accepted

The operator you're looking for is ===. It doesn't work on pure primitive entities, but it does work on references to those entities. The opposite test is !==.

Object a = 5, b = 5;
if(a === b) {
    System.debug('A and B are the same object.');
} else {
    // This will be output
    System.debug('A and B are not the same object.');
}

Object a = 5, b = a;
if(a === b) {
    // This will be output
    System.debug('A and B are the same object.');
} else {
    System.debug('A and B are not the same object.');
}

If you try to use Integer directly, for example, you'll get a compile error:

Integer a = 5, b = 5;
if(a === b)  {  // compile error, "equality only allowed for reference types"
share|improve this answer
    
Wow, I missed an obvious one. I never thought to simply store my primitive as Object. Thanks, you win! –  Bob Roberts Jul 15 at 3:50
    
@BobRoberts For what it's worth, I had no idea this would work. It was something of a hunch, and I was surprised when my debug logs confirmed it. –  sfdcfox Jul 15 at 3:51
add comment

Have you looked at the new Type methods?

https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_type.htm#apex_System_Type_equals

Will this accomplish what you are looking to do?

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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