Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java reimplementing the ==

Tags:

java

class

equals

I know, for instance that, in Python, if I reimplement the method __ cmp __ I am modifying the behaviour of ==. I thought that the same thing could be done in Java, reimplementing equals (like, when you reimplement toString, it affects the print), but... No, or, I don't know how (I searched in google and it seems that, you couldn't) Am I right?? equals does not affect the ==?? If so, what's the point of equals?? Thanks

like image 295
mRt Avatar asked Dec 05 '22 00:12

mRt


2 Answers

Python's == operator is the same as .equals() in Java. You can override this with .__cmp__() in Python and .equals() in Java.

Python's is operator is the same as == in Java, and neither of these can be overridden.

like image 184
Greg Hewgill Avatar answered Dec 07 '22 12:12

Greg Hewgill


The operator == compares object references for equality. The equals method is intended to perform value comparison -- for example, two distinct String objects that represent the same sequence of characters will compare equal if you use equals, but not if you use ==.

As far as I know, operator overloading was left out of Java as a matter of language design. (Why the language designers built in an overload for + over String boggles my mind. Convenient, yes, but IMO that's cheating.)

like image 22
Jeffrey Hantin Avatar answered Dec 07 '22 13:12

Jeffrey Hantin