What are the differences between the methods "equals()", "compareTo()", and even "=="?

Asked

Viewed 428 times

8

I am aware that there are differences between comparing objects using equals(), compareTo() and even the operator ==, but in detail what are the differences between them and the care we should take in the use of each?

1 answer

9


An obvious difference between equals(), compareTo() is that they return different things, the first returns a boolean and can already, for example, be used in a if, whereas the second returns a numeric according to equality (0) or if it is smaller (a negative number according to the criterion of that object) or greater (a positive number according to the criterion of that object), so it gives more precise information, not just about being equal or not, so to use in a if you have to compare with one of these numbers to generate a boolean.

In addition the first is available on all objects because it is on Object, the second is only present in types that implement the interface Comparable.

Still the equals() returns a boolean even if the argument is null. O compareTo() throws an exception in this situation, it requires that the objects are valid. Both throws exception if the main object used is null.

The implementation of how to check the equality or compare its content is free and each object does as it sees fit. The equals() will always have an implementation if the object does not provide, but in general this is not an idea buoy.

The operator == always analyzes the value of the variables or literals used, so primitive types analyze the equality of the value of the object (since the value is already the object) and types by reference (class) analyze the equality of reference, so it only gives equal if it is the same object. This is the reason that people break their face when they try to buy String with the operator, even if the content is the same if it is another object is different.

I do not know what will happen now that Java will have types by value that are not primitive, in theory the operator should compare the value of the object, but it has no operator overhead, so either they will abandon it or they have created some rule of it assume the same as the equals(), or something like that, I’m not following the evolution of this new Feature, that will be revolutionary for Java. I think it is taking a long time to come out precisely because it has an incompatibility that needs to be dealt with.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.