Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

9
  • I must be missing something, but IMHO == on objects should simply call (null-safe) equals and something else (e.g., === or System.identityEqual) should be used for the identity comparison. Mixing primitives and objects would be initially forbidden (there was no autoboxing before 1.5) and then some simple rule could be found (e.g. null-safe unbox, then cast, then compare). Commented Nov 17, 2014 at 8:33
  • @maaartinus: A good language design should use separate equality operators for value and reference equality. While I agree that conceptually it would have been possible to have an int==Integer operator return false if the Integer is null, and otherwise compare values, that approach would have been unlike the behavior of == in all other circumstances, where it unconditionally coerces both operands to the same type before comparing them. Personally I wonder if auto-unboxing was put in place in an effort to allow int==Integer to have a behavior that wasn't nonsensical... Commented Nov 17, 2014 at 16:16
  • ...since autoboxing the int and doing a reference comparison would have been silly [but wouldn't always fail]. Otherwise, I see no reason to allow an implicit conversion that can fail with an NPE. Commented Nov 17, 2014 at 16:20
  • I think that my idea is consistent. Just keep it mind that in the better world, == has nothing to do with identityEquals. +++ "separate equality operators for value and reference equality" - but which ones? I'd consider both primitive == and equals as doing value comparison in the sense that equals looks at the value of the reference. +++ When == meant equals, then int==Integer SHOULD do autoboxing and compare the references using null-safe equals. +++ I'm afraid, my idea is not really mine, but just what Kotlin does. Commented Nov 18, 2014 at 2:04
  • @maaartinus: If == never tested reference equality, then it could sensibly perform a null-safe value-equality test. The fact that it does test reference equality, however, severely limits how it can handle mixed reference/value comparisons without inconsistency. Note also that Java is fixed on the notion that operators promote both operands to the same type, rather than yielding special behaviors based upon the combinations of types involved. For example, 16777217==16777216.0f returns true because it performs a lossy conversion of the first operand to float, while a... Commented Nov 18, 2014 at 4:54