开发者

Difference between the two Java operators: != vs !equals

开发者 https://www.devze.com 2023-03-02 12:32 出处:网络
Is this code: elem1!=elem2 equivalent to this one? !elem1.equals(elem2) It compiles both ways, but I\'m still unsure a开发者_运维百科bout it...== (and by extension !=) check for object identity,

Is this code:

elem1!=elem2

equivalent to this one?

!elem1.equals(elem2)

It compiles both ways, but I'm still unsure a开发者_运维百科bout it...


== (and by extension !=) check for object identity, that is, if both of the objects refer to the very same instance. equals checks for a higher level concept of identity, usually whether the "values" of the objects are equal. What this means is up to whoever implemented equals on that particular object. Therefore they are not the same thing.

A common example where these two are not the same thing are strings, where two different instances might have the same content (the same string of characters), in which case a == comparison is false but equals returns true.

The default implementation of equals (on Object) uses == inside, so the results will be same for objects that do not override equals (excluding nulls, of course)


In general, no they're not the same. The first version checks whether elem1 and elem2 are references to the same object (assuming that they're not primitive types). The second version calls a type-specific method to check whether two (possibly distinct) ojects are "equal", in some sense (often, this is just a check that all their member fields are identical).

I don't think this has anything to do with generics, as such.

0

精彩评论

暂无评论...
验证码 换一张
取 消