Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are objects with the same id always equal when comparing them with ==?

If I have two objects o1 and o2, and we know that

id(o1) == id(o2) 

returns true.

Then, does it follow that

o1 == o2 

Or is this not always the case? The paper I'm working on says this is not the case, but in my opinion it should be true!

like image 566
Jonas Kaufmann Avatar asked Jan 04 '16 21:01

Jonas Kaufmann


People also ask

How do you know if two objects are equivalent?

If the two objects have the same values, equals() will return true . In the second comparison, equals() checks to see whether the passed object is null, or if it's typed as a different class. If it's a different class then the objects are not equal.

Can you compare two objects of the same class?

The equals() method of the Object class compare the equality of two objects. The two objects will be equal if they share the same memory address. Syntax: public boolean equals(Object obj)

How does Python check if two objects are equal?

The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and != , except when you're comparing to None .

How do you make two objects equal in Java?

Java determines equality with the equals(Object o) method - two objects a and b are equal iff a. equals(b) and b. equals(a) return true . These two objects will be equal using the base Object definition of equality, so you don't have to worry about that.


1 Answers

Not always:

>>> nan = float('nan') >>> nan is nan True 

or formulated the same way as in the question:

>>> id(nan) == id(nan) True 

but

>>> nan == nan False 

NaN is a strange thing. Per definition it is not equal nor less or greater than itself. But it is the same object. More details why all comparisons have to return False in this SO question.

like image 185
Mike Müller Avatar answered Sep 22 '22 07:09

Mike Müller