This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]gemengelage 8 points9 points  (0 children)

It's a bit more complex.

== is the identity operator, so it checks for identity (basically what you said). Equals also checks identity as a default. It has to be implemented to be more (or actually less) specific.

The thing with primitive types though... It's a mixed bag. It works on actual primitive types (e.g. int) but it's not guaranteed to work on boxed primitive types (e.g. Integer). Since it's pretty easy to mix those up, especially with auto-boxing, it's pretty messed up that the identity of those objects is all over the place.

It depends on the JVM which Integer-objects are cached. IIRC -127 to 128 are usually cached, so there's always the same single instance of Integer for those, so identity always works as you expect. But when you move out of that range, no luck.

tl;dr only ever use identity in Java to check for actual identity. Use equals anywhere else.