The difference between two Java statements:! = Vs! Equals

This code:

elem1!=elem2 

equivalent to this?

 !elem1.equals(elem2) 

It compiles in both directions, but I'm still not sure about that ...

+4
source share
2 answers

== (and by extension != ) check the identity of the object, that is, if both objects belong to the same instance. equals tests the concept of a higher level identity, usually whether the โ€œvaluesโ€ of objects are equal. This means that anyone who implemented equals on this particular object. Therefore, they are not the same thing.

A common example where these two are not the same are strings in which two different instances can have the same content (the same character string), in which case the comparison == false, but equals returns true.

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

+8
source

In general, they are not the same. The first version checks whether elem1 and elem2 references to the same object (provided that they are not primitive types). The second version calls a method specific to a particular type to check whether two (possibly different) projects are "equal" in a 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 per se.

+7
source

All Articles