Proposal: Sameness operators
reinier at zwitserloot.com
Thu Apr 2 11:53:18 PDT 2009
Why must == also run off of compareTo? (Or, alternatively, why do you -
need- an equality-checking operation based on compareTo that isn't
==)? Java cannot enforce contracts in that way; for example, it's
perfectly legal syntactically, eventhough you're breaking the API
contract, to always "return 1;" in response to a compareTo. Unless an
actual compare operation attempts both the stated comparison and the
mathematically equivalent reverse (a < b and b > a) and throws an
exception if the results aren't equal, there's no guarantee that
compareTo makes any sense.
The current situation with boxing primitives is that == and <> and
extremely inconsistent; new Double(5) vs. new Double(5) isn't ==
equal, but they are equal as far as compareTo is concerned.
Nevertheless, people -do- apply comparisons in java. Making it easier
ought to help. To further complicate things, introducing a new
Comparable-like interface that doesn't suffer from these problems as
badly (for example by wanting an enum back instead of a positive/
negative/zero value) will not be compatible with the existing
Comparable, which would be awkard for HashSet.
My point is thus: There is a perfect world, and java doesn't have it.
And it never will. Either we do this, or we give up and never have any
sort of improvement to the comparable situation. If that's the choice,
I want comparator operators, even with the glitches.
On Apr 2, 2009, at 19:42, Mark Thornton wrote:
> Reinier Zwitserloot wrote:
>> The argument that .compareTo should not be used because it isn't
>> entirely congruent with either the meaning of .equals() or the
>> meanings of all the comparison operators (from == to <) on the
>> primitives, just doesn't hold water, for this simple reason:
> I merely meant that if you want to have a set of comparison
> operators with some of them based on compareTo, then they all must
> be based on compareTo --- you can't use equals (or ==) for the
> equality comparisons. Therefore you have three sets of operations
> ==, System.identityHashCode(), plus for some types <, <=, >, >=
> Object.equals(), Object.hashCode()
> All these need to remain clearly distinct because their existing
> behaviour is not always compatible.
> Mark Thornton
More information about the coin-dev