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

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?

Author: Maniero, 2019-12-18

1 answers

's An obvious difference between the equals(), compareTo() that is, they return different things, the first of which returns a boolean and can, for example, be used in the if, while the second one returns a number according to the equality in (0) or less (a negative number in accordance with the criteria that an object), or to the greater of (a positive number in accordance with the criteria of that object), therefore, it gives the most accurate information, it's not just about being the same or not, so in order to use it in a if you need it compare with one of these numbers to generate a boolean.

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

Still equals() returns a boolean even if the argument is null. compareTo() throws an exception in this situation, it requires the objects to be valid. Both throw exception if the primary object used is null.

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

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 the 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 thesis the operator should compare the value of the object, but it has no operator overhead, so either they will abandon this or created some rule from it assume the same as the equals(), or something like that, I'm not this new feature, which will be revolutionary for Java. I think it's taking time to get out precisely because it has a mismatch that it needs to deal with.

 8
Author: Maniero, 2019-12-19 11:14:24